Home Java의 Annotation 알아보기 - @Configuration
Post
Cancel

Java의 Annotation 알아보기 - @Configuration

출처: Package org.springframework.core.annotation / Annotation Interface AliasFor


@Configuration

1
2
3
4
5
6
7
8
9
10
11
12
13
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Configuration {

	@AliasFor(annotation = Component.class)
	String value() default "";

	boolean proxyBeanMethods() default true;

	boolean enforceUniqueMethods() default true;
}
Indicates that a class declares one or more @Bean methods and may be processed by the Spring container to generate bean definitions and service requests for those beans at runtime, for example:

@Configuration 애너테이션은 다음을 가리킨다.
해당 클래스가 하나 이상의 @Bean 메서드를
선언하며, 스프링 컨테이너로 처리된다.
또한, 이 컨테이너는 빈의 정의bean definitions
런타임 때 해당 빈의 서비스 요청을 생성한다.
예시는 다음과 같다.

1
2
3
4
5
6
7
8
9
10
@Configuration
public class AppConfig {

     @Bean
     public MyBean myBean() {
         // 인스턴스화
         // 설정(configure)
         // 빈을 리턴
     }
 }



1. @Configuration 클래스 부트스트랩 과정

Bootstrapping @Configuration classes

1.1. AnnotationConfigApplicationContext를 통한 과정

Via AnnotationConfigApplicationContext

일반적으로는
AnnotationConfigApplicationContext 클래스 또는
웹 전용인 variant를 사용하여
@Configuration
초기화할 수 있다.
전자의 경우에 대한 코드 예제는 다음과 같다.

1
2
3
4
5
6
AnnotationConfigApplicationContext ctx 
    = new AnnotationConfigApplicationContext();
ctx.register(AppConfig.class);
ctx.refresh();
MyBean myBean = ctx.getBean(MyBean.class);
// myBean 사용하는 코드 ~~~

이에 대한 자세한 내용은
AnnotationConfigApplicationContext 공식 문서를,
Servlet 컨테이너의 웹 설정 명령어들에 대해서는
AnnotationConfigWebApplicationContext 부분을 참고하면 된다.

1.2. 스프링<beans> XML을 통한 과정

Via Spring <beans> XML

AnnotationConfigApplicationContext와는 반대로
@Configuration 클래스를 직접 생성하는 것 대신에
스프링 XML 파일에서 일반적으로 <bean> 정의를 이용하여
다음과 같이 @Configuration 클래스를 선언할 수도 있다.

1
2
3
4
 <beans>
    <context:annotation-config/>
    <bean class="com.acme.AppConfig"/>
 </beans>

ConfigurationClassPostProcessor, 그리고
다른 애너테이션 관련 post 프로세서를
활성화하기 위해선
<context:annotation-config>가 필수적이다.
이 프로세서들이 있어야만
@Configuration 클래스를 다룰 수 있다.

1.3. 컴포넌트 스캔을 통한 과정

Via Component scanning

@Configuration에는
@Component 애너테이션이 붙어있으므로
컴포넌트 스캐닝 대상이 된다.
(스프링 XML에선 `` 요소)
그렇기 때문에 다른 @Component처럼
@Autowired/@Inject를 쓰는 이점을 얻는다.
특히, 단일 생성자가 존재할 경우에
해당 생성자에 자동주입autowireing
이뤄지는 건 명백하다.

1
2
3
4
5
6
7
8
9
10
11
12
@Configuration
public class AppConfig {

    private final SomeBean someBean;

    public AppConfig(SomeBean someBean) {
        this.someBean = someBean;
    }

    // @Bean definition using "SomeBean"

}

@Configuration 클래스는
컴포넌트 스캔을 통해서만
초기화가 이뤄지는 건 아니다.
@ComponentScan 애너테이션을 이용하여
다음과 같이 컴포넌트 스캔을 설정configure할 수 있다.

1
2
3
4
5
@Configuration
@ComponentScan("com.acme.app.services")
public class AppConfig {
    // various @Bean definitions ...
}

자세한 내용은
@ComponentScan 문서를 참고하면 된다.

2. 외부의 값을 통한 방법

Bootstrapping @Configuration classes

2.1. Environment API 사용

스프링 Environment@Configuration에 주입하여
외부의 값을 찾아올 수도 있다.

1
2
3
4
5
6
7
8
9
10
11
12
@Configuration
public class AppConfig {

    @Autowired Environment env;

    @Bean
    public MyBean myBean() {
        MyBean myBean = new MyBean();
        myBean.setName(env.getProperty("bean.name"));
        return myBean;
    }
}

하나 이상의 PropertySource 클래스 객체에 있는
Environment를 통해 사용된 속성들과, 그리고
@Configuration 클래스는
@PropertySource 애너테이션을 이용하는 Environment 객체에
속성 소스들을 contribute 한다.
다음 예제를 참고할 수 있다.

1
2
3
4
5
6
7
8
9
10
11
@Configuration
@PropertySource("classpath:/com/acme/app.properties")
public class AppConfig {

    @Inject Environment env;

    @Bean
    public MyBean myBean() {
        return new MyBean(env.getProperty("bean.name"));
    }
}

자세한 내용은
Environment@PropertySource 문서를 참고하면 된다.

2.2. @Value 애너테이션 사용

@Value 애너테이션을 통하여
외부의 값이 @Configuration 클래스로 주입될 수 있다.

1
2
3
4
5
6
7
8
9
10
11
@Configuration
@PropertySource("classpath:/com/acme/app.properties")
public class AppConfig {

    @Value("${bean.name}") String beanName;

    @Bean
    public MyBean myBean() {
        return new MyBean(beanName);
    }
}

이러한 접근은
스프링의 PropertySourcesPlaceholderConfigurer 클래스와
결합할 때 자주 쓰이는데,
이 클래스는 XML 설정에서
<context:property-placeholder>나, 혹은
관련된 static @Bean 메서드를 통해
명시적으로 @Configuration 클래스에서
자동으로 활성화 된다.

그러나, 주지해야 할 부분은
그러한 @Bean 메서드를 통해
PropertySourcesPlaceholderConfigurer 클래스를
명시적으로 등록하는 것은
placeholder 구분과 같은 설정을
커스텀하고자 할 때에나 필요하단 점이다.

특히, 빈 포스트-프로세서post-processor
(PropertySourcesPlaceholderConfigurer 등이 있다.)
ApplicationContext에 대한
내장된 값embedded resolver를
등록하지 않았다면,
스프링이 기본 내장 값 resolver를 등록하고
이는 Environment에 등록된 속성 자원에 대응되는
placeholder를 생성하게 될 것이다.
@ImportResource를 이용한 스프링 XML로
@Configuration 클래스들을 합치는 것에 대해선
아래의 섹션에서 다룬다.
그리고 PropertySourcesPlaceholderConfigurer와 같은
BeanFactoryPostProcessor 타입으로 다루는 것은
@Bean의 공식 문서를 참고하면 된다.

(추가 중)

Contents