2013. 7. 29. 16:10

Spring annotation

   spring Framework는 java 5+ 부터 annotaion을 제공 하며, annotation의 사용으로 설정파일을 간결화하고, 객체 또는 메소드의 맵핑을 명확하게 할 수 있다.


목차

@Component 

@Required

@Autowired

@Qualifier

@Resource

@Scope

@PostConstruct

@PreDestroy

@Inject



@Component 


패키지 : org.springframework.stereotype

버젼 : spring 2.5

개요 : <context:component-scan> 태그를 설정파일에 추가하면 해당 어노테이션이 적용된 클래스를 빈으로 등록하게 된다. 범위는 디폴트로 singleton이며 @Scope를 사용하여 지정할 수 있다.

 

설정위치: 클래스 선언부 위 

추가설정 : XML 설정파일에 <context:component-scan>을 정의하고 적용할 기본  패키지를 base-package 속성으로 등록한다.


context:annotation-config 태그는 어노테이션과 관련해서 다음의 BeanPostProcessor를 함께 등록 한다.
           - @Required(RequiedAnnotationBeanPostProcessor)
           - @Autowired(AutowiredAnnotationBeanPostProcessor)
           - @Resource, @PostConstruct, @PreDestory(CommonAnnotationBeanPostProcessor)
           - @Configuration(ConfigurationClassPostProcessor)
 
* 그 외 Repository, Service, Controller 포함



예를 들어 <context:component-scan base-package="xxx" />에서 xxx패키지 하위에서 


@Component로 선언된 클래스를 bean으로 자동 등록한다.

bean의 이름은 해당클래스명(첫글자는 소문자)이 사용된다.       

 

<context:component-scan /> 요소에는 scoped-proxy 속성이 존재 한다. 

scoped-proxy 속성은 <aop:scoped-poxy/> 요소처럼 WebApplicationContext 에서만 유효하며 

"session", "globalSession", "request" 이외의 scope는 무시 되며 아래의 3가지 값을 설정 할 수 있다.

 

 

        no : proxy를 생성하지 않는다.(기본값)

        interfaces : JDK Dynamic Proxy를 이용한 Proxy 생성

        targetClass : 클래스에 대해 프록시를 생성(CGLIB를 이용한 Proxy 생성)

 

 

 -  사용 예


@Component
     @Scope("prototype")   // 생략하면 싱글톤
     public class Test {
            .....
     }


- CGLIB

   기존의 자바 클래스파일로부터 자바의 소스코드를 동적으로 생성하는 라이브러리(자바 소스 변경)

 

http://sourceforge.net/projects/cglib/

 

 

- 스캔 대상 클래스 범위 지정하기

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

 


           
           
      
 


위와 같이 <context:include-filter> 태그와 <context:exclude-filter> 태그는 각각 type 속성과 expresseion 속성을 갖는데, type 속성에 따라 expression 속성에 올 수 있는 값이 달라지는데 type 속성에 입력 가능한 값을 다음과 같다

 

* Type 속성에 올 수 있는 값

 

     annotation : 클랙스에 지정한 어노테이션이 적용됐는지의 여부

            expression 속성에서는 "org.example.SomeAnnotation"와 같은 어노테이션 이름을 입력한다.

      assignable : 클래스가 지정한 타입으로 할당 가능한지의 여부. 

            expression 속성에는 "org.exampleSomeClass" 와 같은 타입 이름을 입력한다.

      regex : 클래스 이름이 정규 표현식에 매칭되는 지의 여부.

           expression 속성에는 "org\.example\.Default.*" 와 같이 정규표현식을 입력한다.

      aspectj : 클래스 이름이 AspectJ 의 표현식에 매칭되는 지의 여부.

          expression 속성에는 "org.example..*Service+" 와 같이 AspectJ 의 표현식을 입력한다.

 

 

@Required 

 

패키지 : org.springframework.beans.factory.annotation

버젼 : spring 2.0

Required 어노테이션은 필수 프로퍼티임을 명시하는 것으로 필수 프로퍼티를 설정하지 않을 경우 

빈 생성시 예외를 발생시킨다.


설정위치 : setter 메소드

추가설정 

<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor" /> 클래스를 빈으로 등록시켜줘야 한다. 

해당 설정 대신에<context:annotation-config> 태그를 사용해도 된다.

 

    - 1단계 : 코드내에 프로퍼티 설정 메소드에 @Required 어노테이션을 붙인다.


import org.springframework.beans.factory.annotation.Required
     public class TestBean {
         private TestDao testDao;
  
         @Required
         public void setTestDao(TestDao testDao) {
            this.testDao = testDao;
         }
     }


- 2단계 : 스프링 설정 파일에 RequiredAnnotationBeanPostProcessor 클래스를 빈으로 등록



 
    
          

    


RequiredAnnotationBeanPostProcessor 클래스는 스프링 컨테이너에 등록된 bean 객체를 조사하여 @Required 어노테이션으로 설정되어 있는 프로퍼티의 값이 설정되어 있는지 검사하고 설정되어있지 않으면 bean 생성시 예외를 발생시킨다.

 

     RequiredAnnotationBeanPostProcessor 클래스를 빈으로 등록하지 않고

     <context:annotation-config> 다음과 같이 태그를 이용할 수도 있다.



     

       

     


@Autowired  

 

 패키지 : org.springframework.beans.factory.annotation

버젼 : spring 2.5

개요 : 오토 와이어링 어노테이션은 의존관계를 자동설정할 때 사용하며 타입을 이용하여 의존하는 객체를 삽입해 준다. 그러므로 해당 타입의 빈객체가 존재하지 않거나 또는 2개 이상 존재할 경우 스프링은 예외를 발생시키게 된다.


설정 위치 : 생성자, 필드, 메소드(setter메소드가 아니여도 된다)

추가설정 : <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" /> 클래스를 빈으로 등록시켜줘야 한다. 해당 설정 대신에 <context:annotation-config> 태그를 사용해도 된다.


옵션 : required - @Autowired어노테이션을 적용한 프로퍼티에 대해 설정할 필요가 없는 경우에 false값을 주며 이때 해당 프로퍼티가 존재하지 않더라도 스프링은 예외를 발생시키지 않는다.

 

@Autowired(required=false)로 선언한다. (기본값은 true)

 


특징 : byType으로 의존관계를 자동으로 설정할 경우 같은 타입의 빈이 2개 이상 존재하게 되면 예외가 발생하는데, Autowired도 이러한 문제가 발생한다. 이럴 때 @Qualifier를 사용하면 동일한 타입의 빈 중 특정 빈을 사용하도록 하여 문제를 해결할 수 있다.

 

       @Autowired

       @Qualifier("test")

       private Test test;

 


@Qualifier


패키지 : org.springframework.beans.factory.annotation

버젼 : spring 2.5

개요 : 콸리파이어 어노테이션은 @Autowired의 목적에서 동일 타입의 빈객체가 존재시 특정빈을 삽입할 수 있게 설정한다. @Qualifier("mainBean")의 형태로 @Autowired와 같이 사용하며 해당 <bean>태그에 <qualifire value="mainBean" /> 태그를 선언해주어야 한다. 메소드에서 두개이상의 파라미터를 사용할 경우는 파라미터 앞에 선언해야한다.


설정위치 : @Autowired 어노테이션과 함께 사용된다.

추가설정 : 동일타입의 빈객체 설정에서 <qualifier value="[alias명]" />를 추가해 준다.

옵션 : name - alias명



  
  
  
 
 
 

 

@Resource 


개요 : 자바 6버전 및 JEE5 버전에 추가된 것으로 어플리케이션에서 필요로 하는 자원을 자동 연결할 때 사용 한다. 스프링 2.5 부터 지원하는 어노테이션으로 스프링에서는 의존하는 빈 객체를 전달할 때 사용하다.

              @Autowired 와 같은 기능을 하며 @Autowired와 차이점은 @Autowired는 타입으로(by type),  @Resource는 이름으로(by name)으로 연결시켜준다는 것이다.


설정위치 : 프로퍼티, setter 메소드


추가설정 : <bean class="org.springframework.beans.factory.annotation.CommonAnnotationBeanPostProcessor"/> 클래스를 빈으로 등록시켜줘야 한다. 해당 설정 대신에 <context:annotation-config> 태그를 사용해도 된다.

옵션 : name 

      name속성에 자동으로 연결될 빈객체의 이름을 입력한다.

      @Resource(name="testDao")

 

CommonAnnotationBeanPostProcessor 클래스를 설정파일에 빈객체로 등록하여 어노테이션을 적용시킨다.



 
    
          

    


예제


public class UserService
{
        @Resource(name="user2")
 private User user;  
        //UserImpl user2 = new UserImpl();
        //User user = user2;

 public void setUser(User user)
 {
  this.user = user;
 }
 public String result()
 {
  return user.getData();
 }
}


@Scope 


패키지 : org.springframework.beans.factory.annotation

개요 : 스프링은 기본적으로 빈의 범위를 "singleton" 으로 설정한다. "singleton" 이 아닌 다른범위를 지정하고 싶다면 @Scope 어노테이션을 이용하여 범위를 지정한다.

설정 : prototype, singleton, request, session, globalSession

 

사용 예 - 1


@Component
     @Scope(value="prototype")
     public class Worker {
            :
     }
 


사용 예 - 2


@Component
    @Scope(value="prototype", proxyMode=ScopedProxyMode.TARGET_CLASS)
    public class Worker {
           :
    }


 

@PostConstruct, @PreDestroy, @Inject 


@PostConstruct

패키지 : javax.annotation

버젼 : jdk1.6, spring 2.5

개요 : 의존하는 객체를 설정한 이후에 초기화 작업을 수행하기 위해 사용

설정위치 : 초기화 작업 수행 메소드

추가설정 : CommonAnnotationBeanPostProcessor 클래스를 빈으로 등록시켜줘야 한다. 해당 설정 대신에 <context:annotation-config> 태그를 사용해도 된다.


-예제


@PostConstruct
 public void init()
 {
  System.out.println("객체 생성 후 내가 먼저 실행된다.");
 }



@PreDestroy

패키지 : javax.annotation

버젼 : jdk1.6, spring 2.5

개요 : 컨테이너에서 객체를 제거하기 전에 해야할 작업을 수행하기 위해 사용

설정위치 : 해당 작업 메소드

추가설정 : CommonAnnotationBeanPostProcessor 클래스를 빈으로 등록시켜줘야 한다. 해당 설정 대신에 <context:annotation-config> 태그를 사용해도 된다.

 

@Inject

개요 : JSR-330 표준 Annotation으로 Spring 3 부터 지원하는 Annotation이다. 특정 Framework에 종속되지 않은 어플리케이션을 구성하기 위해서는 @Inject를 사용할 것을 권장한다. @Inject를 사용하기 위해서는 클래스 패스 내에 JSR-330 라이브러리인 javax.inject-x.x.x.jar 파일이 추가되어야 함에 유의해야 한다. 


'Framework > Spring' 카테고리의 다른 글

Spring Framework/ DI / IOC 컨테이너 / POJO  (0) 2013.07.30
Annotation_Spring_MVC_2  (0) 2013.07.29
Annotation  (0) 2013.07.29
Posted by 1+1은?