此版本仍在开发中,尚不被认为是稳定的。对于最新的稳定版本,请使用 Spring Framework 6.2.10spring-doc.cadn.net.cn

基于注释的容器配置

Spring 为基于注释的配置提供了全面的支持,通过使用相关类上的注释来作组件类本身中的metadata,方法或字段声明。如示例:该AutowiredAnnotationBeanPostProcessor, 弹簧用途BeanPostProcessors结合注解,使核心 IOC容器感知特定的注解。spring-doc.cadn.net.cn

例如,@Autowired注释提供了与 Autowiring Collaborators 中描述的相同功能,但具有更细粒度的控制和更广泛的适用性。此外,Spring 还提供对 JSR-250 注释的支持,例如@PostConstruct@PreDestroy,以及支持 JSR-330(Java 依赖注入)注释包含在jakarta.inject包,例如@Inject@Named. 有关这些注释的详细信息可以在相关部分找到。spring-doc.cadn.net.cn

注释注入在外部属性注入之前执行。因此,外部配置(例如,XML 指定的 bean 属性)有效地覆盖了注释对于通过混合方法连接时的属性。spring-doc.cadn.net.cn

从技术上讲,您可以将后处理器注册为单独的 bean 定义,但它们隐式注册在AnnotationConfigApplicationContext已经。spring-doc.cadn.net.cn

在基于 XML 的 Spring 设置中,您可以包含以下配置标签以启用与基于注释的配置混合和匹配:spring-doc.cadn.net.cn

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
		https://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context
		https://www.springframework.org/schema/context/spring-context.xsd">

	<context:annotation-config/>

</beans>

<context:annotation-config/>元素隐式注册以下后处理器:spring-doc.cadn.net.cn

<context:annotation-config/>仅在定义它相同的应用程序上下文中查找 bean 上的注释。这意味着,如果您将<context:annotation-config/>WebApplicationContext对于一个DispatcherServlet, 它只检查@Autowiredbean 在控制器中,而不是服务中。请参阅 DispatcherServlet 了解更多信息。spring-doc.cadn.net.cn