이번에는 애너테이션을 이용하여 애플리케이션을 구성 해보겠습니다. 애너테이션을 이용하면 XML파일을 대체할 수 있습니다.
import com.example.spring_study.ch2.decoupled.HelloWorldMessageProvider;
import com.example.spring_study.ch2.decoupled.MessageProvider;
import com.example.spring_study.ch2.decoupled.MessageRenderer;
import com.example.spring_study.ch2.decoupled.StandardOutMessageRenderer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class HelloWorldConfiguration {
// <bean id="provider" .../>과 동일
@Bean
public MessageProvider provider() {
return new HelloWorldMessageProvider();
}
// <bean id="renderer" .../>과 동일
@Bean
public MessageRenderer renderer() {
MessageRenderer renderer = new StandardOutMessageRenderer();
renderer.setMessageProvider(provider());
return renderer;
}
}
main() 메서드가 구성 클래스에서 빈 구성을 익어 들일 수 있도록 ClassPathXmlApplicationContext 대신 다른 Applicatoin 인터페이스 구현체로 코드를 수정해야 합니다. AnnotationConfigApplicatoinContext 클래스는 매개변수로 구성 클래스를 받아 빈을 생성합니다.실행 결과는 이전과 동일합니다.
import com.example.spring_study.ch2.decoupled.MessageRenderer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class HelloWorldSpringAnnotated {
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(HelloWorldConfiguration.class);
MessageRenderer mr = ctx.getBean("renderer", MessageRenderer.class);
mr.render();
}
}