对于最新稳定版本,请使用 Spring Framework 7.0.6spring-doc.cadn.net.cn

使用 AnnotationConfigApplicationContext 实例化 Spring 容器

以下章节记录了 Spring 3.0 中引入的 Spring AnnotationConfigApplicationContext。这一功能强大的 ApplicationContext 实现不仅能够接受 @Configuration 类作为输入,还能够接受普通的 @Component 类以及带有 JSR-330 元数据注解的类。spring-doc.cadn.net.cn

当提供 @Configuration 类作为输入时,@Configuration 类本身会被注册为一个 bean 定义,同时该类中所有声明的 @Bean 方法也会被注册为 bean 定义。spring-doc.cadn.net.cn

当提供 @Component 和 JSR-330 注解的类时,它们会被注册为 bean 定义,并假定在这些类中必要之处使用了诸如 @Autowired@Inject 等依赖注入(DI)元数据。spring-doc.cadn.net.cn

简单构造

与使用 Spring XML 文件作为实例化 ClassPathXmlApplicationContext 的输入类似,您也可以在实例化 @Configuration 时使用 AnnotationConfigApplicationContext 类作为输入。这样就可以完全不使用 XML 来使用 Spring 容器,如下例所示:spring-doc.cadn.net.cn

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 注解的类都可以作为构造函数的输入参数,如下例所示:spring-doc.cadn.net.cn

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 依赖注入注解,例如 @Autowiredspring-doc.cadn.net.cn

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

你可以使用无参构造函数来实例化一个 AnnotationConfigApplicationContext, 然后通过 register() 方法对其进行配置。这种方法在以编程方式构建 AnnotationConfigApplicationContext 时特别有用。以下 示例展示了如何实现这一点:spring-doc.cadn.net.cn

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 类添加注解:spring-doc.cadn.net.cn

@Configuration
@ComponentScan(basePackages = "com.acme") (1)
public class AppConfig  {
	// ...
}
1 此注解启用组件扫描。
@Configuration
@ComponentScan(basePackages = ["com.acme"]) (1)
class AppConfig  {
	// ...
}
1 此注解启用组件扫描。

有经验的 Spring 用户可能熟悉以下示例中所示的来自 Spring context: 命名空间的等效 XML 声明:spring-doc.cadn.net.cn

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

在前面的示例中,com.acme 包会被扫描,以查找所有带有 @Component 注解的类,并将这些类注册为 Spring 容器中的 bean 定义。AnnotationConfigApplicationContext 提供了 scan(String…​) 方法,以支持相同的组件扫描功能,如下例所示:spring-doc.cadn.net.cn

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 定义。

支持基于 Web 的应用程序,使用AnnotationConfigWebApplicationContext

存在一种 WebApplicationContext 类型的 AnnotationConfigApplicationContext,即 AnnotationConfigWebApplicationContext。在配置 Spring 的 ContextLoaderListener Servlet 监听器、Spring MVC 的 DispatcherServlet 等组件时,可以使用此实现。以下 web.xml 片段配置了一个典型的 Spring MVC Web 应用程序(注意其中 contextClass 上下文参数和初始化参数的使用):spring-doc.cadn.net.cn

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