더북(TheBook)

자바 구성을 사용할 때 바뀌는 것은 빈의 정의 방식뿐입니다. 구성 클래스의 빈 선언 메서드에 @Component 대신 @Bean 애너테이션이 사용되기 때문입니다. 다음은 이와 관련된 예제입니다.

예제 3-126 TargetDemo 클래스([[bean-autowiring]] TargetDemo.java)

package com.apress.prospring5.ch3.config;

import com.apress.prospring5.ch3.sandbox.*;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.GenericApplicationContext;

public class TargetDemo {

    @Configuration
    static class TargetConfig {

        @Bean
        public Foo fooImplOne() {
            return new FooImplOne();
        }

        @Bean
        public Foo fooImplTwo() {
            return new FooImplTwo();
        }

        @Bean
        public Bar bar() {
            return new Bar();
        }

        @Bean
        public TrickyTarget trickyTarget() {
            return new TrickyTarget();
        }

    }

    public static void main(String args) {
        GenericApplicationContext ctx =
            new AnnotationConfigApplicationContext(TargetConfig.class);
        TrickyTarget t = ctx.getBean(TrickyTarget.class);
        ctx.close();
    }

}

 

중복 코드를 만들지 않으려고 com.apress.prospring5.ch3.sandbox 패키지의 기존 클래스를 재사용했습니다. 이때 컴포넌트 스캐닝을 활성화하지 않았기 때문에 스테레오 타입 애너테이션을 사용한 빈 선언은 무시됩니다. 앞의 클래스를 실행하면 그전에 수행했던 예제와 같은 결과가 출력됩니다. 전에 언급했듯이 @Bean을 이용해 빈 선언을 하면 @Bean이 적용된 메서드의 이름이 빈 이름이 되므로 @Qualifier 애너테이션으로 구성된 TrickyTarget도 여전히 예상대로 동작합니다.

신간 소식 구독하기
뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.