[인강정리] 07. DI 애플리케이션 작성(4) - Bean 등록 메타정보 구성 전략

2021. 12. 25. 00:14· 국기훈련과정/Spring

1. 빈 관리 전략

 

1-1. XML 단독 사용

- 모든 빈을 명시적으로 XMl에 등록하는 방법.

- 생성되는 모든 빈을 XMl에서 확인할 수 있다는 장점.

- 빈의 개수가 많아지면 어ㅓ지러워짐.

- 여러 개발자가 같은 설정파일을 공유해서 개발하다보면 설정을 동시에 수정하다가 충돌이 일어나기도 함.

- DI에 필요한 적절한 setter 메서드 또는 constructor가 코드 내에 반드시 존재해야 함.

- 개발 중에는 어노테이션 설정방법을 사용하는 것이 유리함.

- 운영 중에는 관리의 편의성을 위해 XML설정으로 변경하는 전략을 취할 수도 있음.

 

1-2. XML과 Bean Scanning의 혼용

- Bean으로 사용될 클래스에 어노테이션을 부여해주면 자동으로 그런 클래스를 찾아서 Bean으로 등록해줌.(빈 스캐닝)

- 어플리케이션에 등록될 Bean이 어떤 것들이 있고, Bean들 간의 의존관계가 어떻게 되는지를 한눈에 파악할 수 없는 것은 단점임.

 

2. 빈 등록 및 의존관계 설정 어노테이션

 

2-1 빈 등록 어노테이션

1) @Component

- 컴포넌트를 나타내는 일반적인 스테레오 타입으로 <bean>태그와 동일한 역할

2) @Repository

- Persistence 레이어, 영속성을 가지는 속성(파일, 데이터베이스)을 가진 클래스

3) @Service

- 서비스 레이어, 비즈니스 로직을 가진 클래스

4) @Controller

- 프레젠테이션 레이어, 웹 어플리케이션에서 웹 요청과 응답을 처리하는 클래스.

 

*2), 3), 4)는 1)을 구체화 한 것이다. 1)이 더 큰 개념이다.

 

2-2 빈 의존관계 주입 어노테이션

 

1) @Autowired

- 정밀한 의존관계 주입이 필요한 경우에 유용함.

- @Autowired는 프로퍼티, setter 메서드, 생성자, 일반메서드에 적용가능.

- 의존하는 객체를 주입할 때 주로 Type을 이용함.

- <property>, <constructor-arg>와 동일한 역할임.

 

2) @Resource

- 마찬가지로 자동 의존 주입 어노테이션.

- @Autowired는 타입으로, @Resource는 이름으로 연결한다는 차이가 있다.

- <property> , setter 메서드에 적용 가능.

- 의존 객체를 주입시 Name을 이용.

 

3) @Value

- 단순한 값을 주입할 때 사용되는 어노테이션.

- @Value("Spring")은 <property ~~ value="abc" />와 동일한 역할

 

4) @Qualifier

- @Autowired 어노테이션과 같이 사용됨.

- @Autowired는 Type으로 찾아서 주입하기 때문에 동일 타입의 Bean 객체가 여러 개 존재하는 경우 특정 Bean을 찾기 위해 @Qualifier를 같이 사용함.

 

2-3 Component Scan을 지원하는 태그

- @Component를 통해 자동으로 빈을 등록하고 @Autowired로 의존관계를 주입받는 어노테이션을 클래스에서 선언하여 사용했을 경우, 해당 클래스가 위치한 특정 패키지를 Scan하기 위한 설정을 XML에 넣어주어야 함.

- <context:component-scan base-package="패키지경로" />

- <context:include-fileter>태그와 <context:exclude-filter> 태그를 같이 사용하면 자동 스캔 대상에 포함시킬 클래스와 포함시키지 않을 클래스를 분리할 수 있다.

 

 

3. 어노테이션을 사용한 POJO 클래스 작성.

 

3-1 StringPrinter.java 어노테이션을 이용해 수정

package myspring.di.annot;

import org.springframework.stereotype.Component;

@Component("stringPrinter")
public class StringPrinter implements Printer {
	private StringBuffer buffer = new StringBuffer();
    
    @Override
    public void print(String message) {
    	buffer.append(message);
    }
    
    public String toString() {
    	return buffer.toString();
    }
}

3-2 ConsolePrinter.java 수정

package myspring.di.annot;

import org.springframework.stereotype.Component;

@Component("consolePrinter")
public class ConsolePrinter implements Printer {
	@Override
    public void print(String message) {
    	System.out.println(message);
    }
}

 

3-3 Hello.java 수정

package myspring.di.annot;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class Hello {

	@Value("Spring")
    private String name;    
    
    @Autowired
    @Qualifier("stringPrinter")
    private Printer printer;
    
    public Hello() {}
    
    public Hello(String name, Printer printer) {
    	this.name = name;
        this.printer = printer;
    }
    
}

 

3-4 빈 설정 XML --> annot.xml 작성

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
	
    <context:component-scan base-package="myspring.di.annot" />

</beans>

 

3-5 DI 테스트 클라이언트 수정 (HelloBeanAnnotTest.java)

** junit, spring-test가 제대로 import되지 않는 문제가 있었는데 maven central repo에서 module로 pom에 추가했더니 안되는 거였음. RELEASE 버전으로 추가를 해줘야 아무 문제가 없이 작동하는 것을 확인하였음.

package myspring.di.annot;

import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import static org.junit.Assert.*;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:/")
public class HelloBeanAnnotTest {
	@Autowired
	ApplicationContext context;
	
	public void test() {
		Hello hello = context.getBean("hello", Hello.class);
		assertEquals("Hello Spring", hello.sayHello());
	}
}

 

4. Property 파일을 이용한 설정 방법

 

4-1. Properties 파일 및 Bean 설정파일 작성

 

value.properties

myname=Spring
myprinter=printer
value1=AOP
value2=Spring
value3=DI
printer1=stringPrinter
printer2=consolePrinter

 

Hello.java 수정

package myspring.di.annot;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class Hello {

	@Value("${myname}")
    private String name;    
    
	/*
	 * @Autowired
	 * 
	 * @Qualifier("stringPrinter")
	 */
	@Resource(name="${printer1}")
    private Printer printer;
    
    public String sayHello() {
    	return "Hello " + name;    	
    }
    
    public void print() {
    	this.printer.print(sayHello());
    }
    
}

 

annot.xml 수정

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
	
	<context:component-scan base-package="myspring.di.annot" />
	
	<context:property-placeholder location="classpath:config/value.properties"/>

</beans>

 

저작자표시 (새창열림)

'국기훈련과정 > Spring' 카테고리의 다른 글

[인강정리] 06. DI 애플리케이션 작성(3) - Bean 의존성 주입 방법  (0) 2021.12.24
[인강정리] 05. DI 애플리케이션 작성(2) - jUnit  (0) 2021.12.24
[인강정리] 04. DI 애플리케이션 작성(1)  (0) 2021.12.24
[인강정리] 03. IoC 컨테이너와 DI  (0) 2021.12.24
[인강정리] 02. Spring 시작하기  (0) 2021.12.24
'국기훈련과정/Spring' 카테고리의 다른 글
  • [인강정리] 06. DI 애플리케이션 작성(3) - Bean 의존성 주입 방법
  • [인강정리] 05. DI 애플리케이션 작성(2) - jUnit
  • [인강정리] 04. DI 애플리케이션 작성(1)
  • [인강정리] 03. IoC 컨테이너와 DI
Purewater
Purewater
Purewater
프로그램 공부 일기장
Purewater
전체
오늘
어제
  • 분류 전체보기 (237)
    • Front-end (8)
      • Vue (8)
    • 포트폴리오 (3)
      • JSP SHOP (1)
      • Travelanner (1)
      • OAuth2 Blog (1)
    • 취업 준비 (70)
      • Spring boot (43)
      • JPA (1)
      • Spring security (14)
      • React (11)
      • 면접 기록 (1)
    • 국기훈련과정 (57)
      • JAVA 복습노트 (12)
      • Oracle SQL (9)
      • Web (15)
      • JSP (6)
      • Spring (10)
      • 프로젝트 (4)
      • Python (1)
    • 알고리즘 문제풀이 (17)
      • Python3 (13)
      • Kotlin (4)
    • 이것저것 지식 (9)
    • 클라우드 서버 (7)
      • Linux (7)
    • Backend (20)
      • node.js (9)
      • JAVA (6)
      • spring boot (5)
    • DB (1)
      • SQL (1)
    • 잡담 (1)
    • 강의 수강 (1)
    • CS 지식 (41)
      • 디자인패턴 (6)
      • 네트워크 (22)
      • 데이터베이스 (4)

블로그 메뉴

  • 대문
  • 태그
  • 방명록
  • 글쓰기

공지사항

인기 글

태그

  • gitignore
  • db
  • PostgreSQL
  • JPA
  • 노드
  • 자바스크립트
  • Postman
  • node
  • 오라클
  • redis
  • Kotlin
  • spring
  • Oracle
  • 디자인패턴
  • GUI
  • git
  • js
  • Java
  • SQL
  • node.js

최근 댓글

최근 글

hELLO · Designed By 정상우.v4.2.2
Purewater
[인강정리] 07. DI 애플리케이션 작성(4) - Bean 등록 메타정보 구성 전략
상단으로

티스토리툴바

개인정보

  • 티스토리 홈
  • 포럼
  • 로그인

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.