Loading...
Spring Framework Reference Documentation 7.0.2의 Instantiating the Spring Container by Using AnnotationConfigApplicationContext의 한국어 번역본입니다.
아래의 경우에 피드백에서 신고해주신다면 반영하겠습니다.
감사합니다 :)
AnnotationConfigApplicationContext다음 섹션에서는 Spring 3.0에서 도입된 Spring의 AnnotationConfigApplicationContext에 대해 문서화합니다.
이 다재다능한 ApplicationContext 구현체는 입력으로 @Configuration class뿐만 아니라 일반
@Component class 및 JSR-330 메타데이터로 어노테이션된 class도 받을 수 있습니다.
@Configuration class가 입력으로 제공되면, @Configuration class 자체가 bean 정의로
등록되고, class 내에 선언된 모든 @Bean 메서드도 bean 정의로 등록됩니다.
@Component 및 JSR-330 class가 제공되면, 이들은 bean 정의으로 등록되며, 필요한 곳에서
@Autowired 또는 @Inject와 같은 DI 메타데이터가 해당 class 내에서 사용된다고 가정합니다.
ClassPathXmlApplicationContext를 인스턴스화할 때 Spring XML 파일이 입력으로 사용되는 것과 거의
같은 방식으로, AnnotationConfigApplicationContext를 인스턴스화할 때 @Configuration class를
입력으로 사용할 수 있습니다. 다음 예제에서 볼 수 있듯이, 이는 Spring 컨테이너를 완전히 XML 없이
사용할 수 있게 해줍니다:
1public static void main(String[] args) { 2 ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class); 3 MyService myService = ctx.getBean(MyService.class); 4 myService.doStuff(); 5}
1import org.springframework.beans.factory.getBean 2 3fun main() { 4 val ctx = AnnotationConfigApplicationContext(AppConfig::class.java) 5 val myService = ctx.getBean<MyService>() 6 myService.doStuff() 7}
앞에서 언급했듯이, AnnotationConfigApplicationContext는 @Configuration class와만
동작하는 것으로 제한되지 않습니다. 어떤 @Component 또는 JSR-330 어노테이션된 class도
다음 예제에서 보듯이 생성자의 입력으로 제공될 수 있습니다:
1public static void main(String[] args) { 2 ApplicationContext ctx = new AnnotationConfigApplicationContext(MyServiceImpl.class, Dependency1.class, Dependency2.class); 3 MyService myService = ctx.getBean(MyService.class); 4 myService.doStuff(); 5}
1import org.springframework.beans.factory.getBean 2 3fun main() { 4 val ctx = AnnotationConfigApplicationContext(MyServiceImpl::class.java, Dependency1::class.java, Dependency2::class.java) 5 val myService = ctx.getBean<MyService>() 6 myService.doStuff() 7}
앞의 예제는 MyServiceImpl, Dependency1, 그리고 Dependency2가 @Autowired와 같은 Spring
의존성 주입 어노테이션을 사용한다고 가정합니다.
register(Class<?>…)no-arg 생성자를 사용하여 AnnotationConfigApplicationContext를 인스턴스화한 다음
register() 메서드를 사용하여 구성할 수 있습니다. 이 접근 방식은
AnnotationConfigApplicationContext를 프로그래밍 방식으로 빌드할 때 특히 유용합니다.
다음 예제는 그 방법을 보여줍니다:
1public static void main(String[] args) { 2 AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); 3 ctx.register(AppConfig.class, OtherConfig.class); 4 ctx.register(AdditionalConfig.class); 5 ctx.refresh(); 6 MyService myService = ctx.getBean(MyService.class); 7 myService.doStuff(); 8}
1import org.springframework.beans.factory.getBean 2 3fun main() { 4 val ctx = AnnotationConfigApplicationContext() 5 ctx.register(AppConfig::class.java, OtherConfig::class.java) 6 ctx.register(AdditionalConfig::class.java) 7 ctx.refresh() 8 val myService = ctx.getBean<MyService>() 9 myService.doStuff() 10}
scan(String…)컴포넌트 스캐닝을 활성화하려면, 다음과 같이 @Configuration class에 어노테이션을
추가할 수 있습니다:
1@Configuration 2@ComponentScan(basePackages = "com.acme") // (1) 3public class AppConfig { 4 // ... 5}
| 1 | 이 어노테이션은 컴포넌트 스캐닝을 활성화합니다. |
1@Configuration 2@ComponentScan(basePackages = ["com.acme"]) // (1) 3class AppConfig { 4 // ... 5}
| 1 | 이 어노테이션은 컴포넌트 스캐닝을 활성화합니다. |
숙련된 Spring 사용자는 다음 예제에 표시된 것처럼 Spring의
context:네임스페이스에서 동일한 XML 선언에 익숙할 수 있습니다:1<beans> 2 <context:component-scan base-package="com.acme"/> 3</beans>
앞의 예제에서, com.acme 패키지는 @Component로 어노테이션된 class를 찾기 위해
스캔되며, 이러한 class는 컨테이너 내에서 Spring bean 정의로 등록됩니다.
AnnotationConfigApplicationContext는 다음 예제에서 보듯이 동일한 컴포넌트 스캐닝
기능을 허용하기 위해 scan(String…) 메서드를 노출합니다:
1public static void main(String[] args) { 2 AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); 3 ctx.scan("com.acme"); 4 ctx.refresh(); 5 MyService myService = ctx.getBean(MyService.class); 6}
1fun main() { 2 val ctx = AnnotationConfigApplicationContext() 3 ctx.scan("com.acme") 4 ctx.refresh() 5 val myService = ctx.getBean<MyService>() 6}
@Configurationclass는@Component로 메타-어노테이션 되어 있으므로 컴포넌트 스캐닝의 후보가 된다는 점을 기억하십시오. 앞의 예제에서,AppConfig가com.acme패키지(또는 그 하위의 어떤 패키지) 내에 선언되어 있다고 가정하면,scan()호출 중에 이를 감지합니다.refresh()시점에, 해당@Bean메서드가 모두 처리되어 컨테이너 내에서 bean 정의로 등록됩니다.
AnnotationConfigWebApplicationContextAnnotationConfigApplicationContext의 WebApplicationContext 변형은
AnnotationConfigWebApplicationContext로 제공됩니다. 이 구현체는 Spring
ContextLoaderListener 서블릿 리스너, Spring MVC DispatcherServlet 등을
구성할 때 사용할 수 있습니다. 다음 web.xml 스니펫은 전형적인 Spring MVC 웹
애플리케이션을 구성합니다(contextClass context-param 및 init-param의 사용에
주의하십시오):
1<web-app> 2 <!-- Configure ContextLoaderListener to use AnnotationConfigWebApplicationContext 3 instead of the default XmlWebApplicationContext --> 4 <context-param> 5 <param-name>contextClass</param-name> 6 <param-value> 7 org.springframework.web.context.support.AnnotationConfigWebApplicationContext 8 </param-value> 9 </context-param> 10 11 <!-- Configuration locations must consist of one or more comma- or space-delimited 12 fully-qualified @Configuration classes. Fully-qualified packages may also be 13 specified for component-scanning --> 14 <context-param> 15 <param-name>contextConfigLocation</param-name> 16 <param-value>com.acme.AppConfig</param-value> 17 </context-param> 18 19 <!-- Bootstrap the root application context as usual using ContextLoaderListener --> 20 <listener> 21 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 22 </listener> 23 24 <!-- Declare a Spring MVC DispatcherServlet as usual --> 25 <servlet> 26 <servlet-name>dispatcher</servlet-name> 27 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 28 <!-- Configure DispatcherServlet to use AnnotationConfigWebApplicationContext 29 instead of the default XmlWebApplicationContext --> 30 <init-param> 31 <param-name>contextClass</param-name> 32 <param-value> 33 org.springframework.web.context.support.AnnotationConfigWebApplicationContext 34 </param-value> 35 </init-param> 36 <!-- Again, config locations must consist of one or more comma- or space-delimited 37 and fully-qualified @Configuration classes --> 38 <init-param> 39 <param-name>contextConfigLocation</param-name> 40 <param-value>com.acme.web.MvcConfig</param-value> 41 </init-param> 42 </servlet> 43 44 <!-- map all requests for /app/* to the dispatcher servlet --> 45 <servlet-mapping> 46 <servlet-name>dispatcher</servlet-name> 47 <url-pattern>/app/*</url-pattern> 48 </servlet-mapping> 49</web-app>
프로그래밍 방식 사용 사례의 경우,
GenericWebApplicationContext는AnnotationConfigWebApplicationContext의 대안으로 사용할 수 있습니다. 자세한 내용은GenericWebApplicationContextjavadoc을 참조하십시오.
Basic Concepts: @Bean and @Configuration
Using the @Bean Annotation