티스토리 뷰

Java/Spring

Annotation을 이용한 Bean 등록

작은 거인 2017. 1. 7. 16:37

Bean 등록 Annotation


@Component

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

@Repository

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

@Service

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

@Controller

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

 - @Repository, @Service, @Controller는 더 특정한 유즈케이승 대한 @Component의 구체화된 형태이다.



Bean 의존관계 주입 Annotation


@Autowired, @Resource annotation은 의존하는 객체를 자동으로 주입해주는 annotation이다.

@Autowired

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

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

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

 @Autowired는 <property>, <contructor-arg> 태그와 동일한 역할.

@Resource

 어플리케이션에서 필요로 하는 자원을 자동 연결할 때 사용

 @Resource는 poperty, setter 메서드에 적용 가능

 의존하는 객체를 주입할 때 주로 Name을 이용

@Value

 단순한 값을 주입할 때 사용되는 annotation.

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

@Qualifier

 @Qualifier는 @Autowired annotation과 같이 사용.

 @Autowired는 타입으로 찾아서 주입하므로, 동일 타입의 Bean 객체가 여러 개 존재할 때 특정 Bean을 찾기 

 위해 사용



<context:component-scan> 태그


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

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


<context:include-filter>태그와 <context:exclude-filter> 태그를 사용해 자동 스캔 대상에 포함시킬 클래스와 포함시키지 않을 클래스를 구체적으로 명시 가능.


<<Give it a shot>>


ConsolePrinter.class


StringPrinter.class


Hello.class

* 왜 ConsolePrinter와 StringPrinter는 @Component에 아큐먼트로 이름을 넣었을까?

 -> @Autowired 는 타입으로 스캔하기 때문에 같은 Printer Type이라 컨이너가 구분할 수 없기 때문.


annot.xml (Bean Configuration File)


HelloBeanTestAnnot.class

* jUnit 모듈을 사용하여 테스트.


<<Give it a shot>> - Way of Using Property File (property file을 이용한 방법)


value.properties


Hello.class


annot.xml

* 결과 생략


댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함