使用 AnnotationConfigApplicationContext 实例化 Spring 容器

以下章节介绍了 Spring 3.0 中引入的 Spring AnnotationConfigApplicationContext。 这个多功能的 ApplicationContext 实现不仅能够接受 @Configuration 类作为输入, 还能接受普通的 @Component 类和使用 JSR-330 元数据注解的类。 当提供 @Configuration 类作为输入时,@Configuration 类本身会被注册为 bean 定义, 并且类中所有声明的 @Bean 方法也会被注册为 bean 定义。 当提供 @Component 和 JSR-330 类时,它们会被注册为 bean 定义, 并且假定在这些类中必要时使用了 @Autowired@Inject 等 DI 元数据。

简单构造

与实例化 ClassPathXmlApplicationContext 时使用 Spring XML 文件作为输入的方式类似, 您可以在实例化 AnnotationConfigApplicationContext 时使用 @Configuration 类作为输入。 这使得 Spring 容器可以完全脱离 XML 使用,如下例所示:

  • Java

  • Kotlin

public static void main(String[] args) {
	ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
	MyService myService = ctx.getBean(MyService.class);
	myService.doStuff();
}
import org.springframework.beans.factory.getBean

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

如前所述,AnnotationConfigApplicationContext 不仅限于与 @Configuration 类一起工作。 任何 @Component 或 JSR-330 注解的类都可以作为输入提供给构造函数,如下例所示:

  • Java

  • Kotlin

public static void main(String[] args) {
	ApplicationContext ctx = new AnnotationConfigApplicationContext(MyServiceImpl.class, Dependency1.class, Dependency2.class);
	MyService myService = ctx.getBean(MyService.class);
	myService.doStuff();
}
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()
}

前面的例子假设 MyServiceImplDependency1Dependency2 使用了 Spring 依赖注入注解,例如 @Autowired

使用 register(Class<?>…​) 以编程方式构建容器

您可以使用无参构造函数实例化 AnnotationConfigApplicationContext, 然后使用 register() 方法对其进行配置。 当以编程方式构建 AnnotationConfigApplicationContext 时,这种方法特别有用。 以下示例展示了如何实现:

  • Java

  • Kotlin

public static void main(String[] args) {
	AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
	ctx.register(AppConfig.class, OtherConfig.class);
	ctx.register(AdditionalConfig.class);
	ctx.refresh();
	MyService myService = ctx.getBean(MyService.class);
	myService.doStuff();
}
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()
}

使用 scan(String…​) 启用组件扫描

要启用组件扫描,您可以按如下方式注解您的 @Configuration 类:

Java
@Configuration
@ComponentScan(basePackages = "com.acme") [id="CO1-1"][id="CO1-1"][id="CO1-1"](1)
public class AppConfig  {
	// ...
}
<1>  此注解启用组件扫描。
Kotlin
@Configuration
@ComponentScan(basePackages = ["com.acme"]) [id="CO2-1"][id="CO1-2"][id="CO2-1"](1)
class AppConfig  {
	// ...
}
<1>  此注解启用组件扫描。

经验丰富的 Spring 用户可能熟悉 Spring context: 命名空间中等效的 XML 声明,如下例所示:

<beans>
	<context:component-scan base-package="com.acme"/>
</beans>

在前面的示例中,扫描 com.acme 包以查找任何 @Component 注解的类, 并将这些类注册为容器中的 Spring bean 定义。 AnnotationConfigApplicationContext 暴露了 scan(String…​) 方法以实现相同的组件扫描功能,如下例所示:

  • Java

  • Kotlin

public static void main(String[] args) {
	AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
	ctx.scan("com.acme");
	ctx.refresh();
	MyService myService = ctx.getBean(MyService.class);
}
fun main() {
	val ctx = AnnotationConfigApplicationContext()
	ctx.scan("com.acme")
	ctx.refresh()
	val myService = ctx.getBean<MyService>()
}

请记住,@Configuration 类通过 元注解 @Component 进行注解,因此它们是组件扫描的候选者。 在前面的示例中,假设 AppConfig 声明在 com.acme 包(或其下的任何包)中, 它将在调用 scan() 期间被检测到。 在 refresh() 之后,其所有 @Bean 方法都将被处理并注册为容器中的 bean 定义。

AnnotationConfigWebApplicationContext Web 应用程序的支持

AnnotationConfigApplicationContextWebApplicationContext 变体可以通过 AnnotationConfigWebApplicationContext 获得。 您可以在配置 Spring ContextLoaderListener Servlet 监听器、Spring MVC DispatcherServlet 等时使用此实现。 以下 web.xml 片段配置了一个典型的 Spring MVC Web 应用程序(请注意 contextClass context-param 和 init-param 的使用):

<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>

对于编程用例,GenericWebApplicationContext 可以作为 AnnotationConfigWebApplicationContext 的替代方案。 有关详细信息,请参阅 GenericWebApplicationContext 的 Javadoc。