[Spring] HelloWorld 애플리케이션 만들기 (3)

extory1004·2022년 2월 13일

SpringFramework

목록 보기
3/4

이번에는 애너테이션을 이용하여 애플리케이션을 구성 해보겠습니다. 애너테이션을 이용하면 XML파일을 대체할 수 있습니다.

구성 클래스는 빈 정의 내용을 담고 있는 @Configuration 애너테이션이 붙은 클래스이거나 @ComponentScan 에너테이션을 붙여 애플리케이션 내의 빈 정의를 스스로 찾는 클래스입니다.

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();
    }
}
profile
코딩하는 대학생

0개의 댓글