Home [Spring] 1.12.2. Instantiating the Spring Container by Using AnnotationConfigApplicationContext
Post
Cancel

[Spring] 1.12.2. Instantiating the Spring Container by Using AnnotationConfigApplicationContext

1.12.2. Instantiating the Spring Container by Using AnnotationConfigApplicationContext

The following sections document Spring’s AnnotationConfigApplicationContext, introduced in Spring 3.0. This versatile ApplicationContext implementation is capable of accepting not only @Configuration classes as input but also plain @Component classes and classes annotated with JSR-330 metadata.

  • 다음 섹션은 Spring 3.0에서 소개된 Spring’s AnnotationConfigApplicationContext를 document한다.
  • 이 다양한 목적으로의 ApplicationContext 구현은 input 으로의 @Configuration 클래스뿐만 아니라 JSR-330 메타데이터로 주석을 단 클래스와 일반 @Component 클래스도 수용할 수 있다.

When @Configuration classes are provided as input, the @Configuration class itself is registered as a bean definition and all declared @Bean methods within the class are also registered as bean definitions.

  • @Configuration 클래스가 입력으로 제공되면, @Configuration 클래스 자체가 bean definition으로 등록되고 클래스 내에 선언된 @Bean 메서드도 모두 bean definitions로 등록된다.

When @Component and JSR-330 classes are provided, they are registered as bean definitions, and it is assumed that DI metadata such as @Autowired or @Inject are used within those classes where necessary.

  • @Component 및 JSR-330 클래스가 제공되면 bean definitions로 등록되며, 필요한 경우 해당 클래스 내에서 @Autowired 또는 @Inject와 같은 DI 메타데이터가 사용되는 것으로 가정한다.

Simple Construction

In much the same way that Spring XML files are used as input when instantiating a ClassPathXmlApplicationContext, you can use @Configuration classes as input when instantiating an AnnotationConfigApplicationContext. This allows for completely XML-free usage of the Spring container, as the following example shows:

  • ClassPathXmlApplicationContext를 인스턴스화할 때 스프링 XML 파일이 입력으로 사용되는 것과 거의 동일한 방법으로, AnnotationConfigApplicationContext를 인스턴스화할 때 @Configuration 클래스를 입력으로 사용할 수 있다.
  • 이를 통해 다음 예에서 알 수 있듯이 스프링 컨테이너를 완전히 XML 없이(completely XML-free usage) 사용할 수 있다.
1
2
3
4
5
6
7
import org.springframework.beans.factory.getBean

fun main() {
    val ctx = AnnotationConfigApplicationContext(AppConfig::class.java)
    val myService = ctx.getBean<MyService>()
    myService.doStuff()
}

As mentioned earlier, AnnotationConfigApplicationContext is not limited to working only with @Configuration classes. Any @Component or JSR-330 annotated class may be supplied as input to the constructor, as the following example shows:

  • 앞에서 언급한 바와 같이 AnnotationConfigApplicationContext@Configuration 클래스로만 작업하는 것에 국한되지 않는다.
  • @Component 또는 JSR-330 주석 처리된 클래스는 다음 예와 같이 생성자에게 입력으로 제공될 수 있다.
1
2
3
4
5
6
7
import org.springframework.beans.factory.getBean

fun main() {
    val ctx = AnnotationConfigApplicationContext(MyServiceImpl::class.java, Dependency1::class.java, Dependency2::class.java)
    val myService = ctx.getBean<MyService>()
    myService.doStuff()
}

The preceding example assumes that MyServiceImpl, Dependency1, and Dependency2 use Spring dependency injection annotations such as @Autowired.

  • 앞의 예에서는 MyServiceImpl, Dependency1Dependency2@Autorwired와 같은 Spring dependency injection annotations을 사용한다고 가정한다.

Building the Container Programmatically by Using register(Class<?>…)

You can instantiate an AnnotationConfigApplicationContext by using a no-arg constructor and then configure it by using the register() method. This approach is particularly useful when programmatically building an AnnotationConfigApplicationContext. The following example shows how to do so:

  • no-arg constructor를 사용하여 AnnotationConfigApplicationContext를 인스턴스화한 다음 register() 메서드를 사용하여 구성할 수 있다.
  • 이 접근방식은 특히 AnnotationConfigApplicationContext를 프로그래밍 방식으로 구축할 때 유용하다.
  • 다음 예제는 이를 수행하는 방법을 보여준다.
1
2
3
4
5
6
7
8
9
10
import org.springframework.beans.factory.getBean

fun main() {
    val ctx = AnnotationConfigApplicationContext()
    ctx.register(AppConfig::class.java, OtherConfig::class.java)
    ctx.register(AdditionalConfig::class.java)
    ctx.refresh()
    val myService = ctx.getBean<MyService>()
    myService.doStuff()
}

Enabling Component Scanning with scan(String…)

To enable component scanning, you can annotate your @Configuration class as follows:

  • 구성 요소 검색을 활성화하려면 다음과 같이 @Configuration 클래스에 annotation을 달 수 있다.
1
2
3
4
5
@Configuration
@ComponentScan(basePackages = ["com.acme"]) // This annotation enables component scanning.
class AppConfig  {
    // ...
}

Experienced Spring users may be familiar with the XML declaration equivalent from Spring’s context: namespace, shown in the following example:

  • 숙련된 스프링 사용자는 다음 예에서 볼 수 있는 스프링의 context: 네임스페이스와 동등한 XML 선언에 익숙할 수 있다.
1
2
3
<beans>
    <context:component-scan base-package="com.acme"/>
</beans>

In the preceding example, the com.acme package is scanned to look for any @Component-annotated classes, and those classes are registered as Spring bean definitions within the container. AnnotationConfigApplicationContext exposes the scan(String…) method to allow for the same component-scanning functionality, as the following example shows:

  • 앞의 예에서 com.acme 패키지를 스캔하여 @Component-annotated 클래스를 찾으며, 해당 클래스는 container 내에서 Spring bean definitions으로 등록된다.
  • AnnotationConfigApplicationContext는 다음 예시와 같이 동일한 component-scanning 기능을 허용하기 위해 scan(String…) 방법을 노출한다.
1
2
3
4
5
6
fun main() {
    val ctx = AnnotationConfigApplicationContext()
    ctx.scan("com.acme")
    ctx.refresh()
    val myService = ctx.getBean<MyService>()
}

Remember that @Configuration classes are meta-annotated with @Component, so they are candidates for component-scanning. In the preceding example, assuming that AppConfig is declared within the com.acme package (or any package underneath), it is picked up during the call to scan(). Upon refresh(), all its @Bean methods are processed and registered as bean definitions within the container.

  • @Configuration 클래스는 @Component와 함께 meta-annotated 된 클래스라는 것을 기억하면, 그들은 component-scanning를 위한 후보자가 된다.
  • 앞의 예에서 AppConfigcom.acme 패키지(또는 아래의 모든 패키지) 내에서 선언된다고 가정하면, scan()을 호출하는 동안 AppConfig가 선택된다.
  • refresh() 시 모든 @Bean methods가 처리되어 container 내에서 bean definitions로 등록된다.

Support for Web Applications with AnnotationConfigWebApplicationContext

A WebApplicationContext variant of AnnotationConfigApplicationContext is available with AnnotationConfigWebApplicationContext. You can use this implementation when configuring the Spring ContextLoaderListener servlet listener, Spring MVC DispatcherServlet, and so forth. The following web.xml snippet configures a typical Spring MVC web application (note the use of the contextClass context-param and init-param):

  • AnnotationConfigApplicationContextWebApplicationContext 변형(variant)은 AnnotationConfigWebApplicationContext와 함께 사용할 수 있다.
  • 이 구현은 Spring ContextLoaderListener servlet listener, Spring MVC DispatcherServlet 등을 구성할 때 사용할 수 있다.
  • 다음 web.xml 코드 조각은 일반적인 Spring MVC 웹 응용 프로그램을 구성한다(contextClass context-parameter 및 init-param 사용 참고).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<web-app>
    <!-- Configure ContextLoaderListener to use AnnotationConfigWebApplicationContext
        instead of the default XmlWebApplicationContext -->
    <context-param>
        <param-name>contextClass</param-name>
        <param-value>
            org.springframework.web.context.support.AnnotationConfigWebApplicationContext
        </param-value>
    </context-param>

    <!-- Configuration locations must consist of one or more comma- or space-delimited
        fully-qualified @Configuration classes. Fully-qualified packages may also be
        specified for component-scanning -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>com.acme.AppConfig</param-value>
    </context-param>

    <!-- Bootstrap the root application context as usual using ContextLoaderListener -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- Declare a Spring MVC DispatcherServlet as usual -->
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- Configure DispatcherServlet to use AnnotationConfigWebApplicationContext
            instead of the default XmlWebApplicationContext -->
        <init-param>
            <param-name>contextClass</param-name>
						<param-value>
                org.springframework.web.context.support.AnnotationConfigWebApplicationContext
            </param-value>
        </init-param>
        <!-- Again, config locations must consist of one or more comma- or space-delimited
            and fully-qualified @Configuration classes -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>com.acme.web.MvcConfig</param-value>
        </init-param>
    </servlet>

    <!-- map all requests for /app/* to the dispatcher servlet -->
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/app/*</url-pattern>
    </servlet-mapping>
</web-app>

References

This post is licensed under CC BY 4.0 by the author.

[Spring] 1.12.1. Basic Concepts: @Bean and @Configuration

[Spring] 1.12.3. Using the @Bean Annotation