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

基于注解的容器配置

Spring 提供了对基于注解的配置的全面支持,通过在相关类、方法或字段声明上使用注解,直接在组件类本身中操作元数据。如 示例:AutowiredAnnotationBeanPostProcessor 中所述, Spring 使用 BeanPostProcessors 与注解结合,使核心 IOC 容器能够识别特定的注解。spring-doc.cadn.net.cn

例如,@Autowired 注解提供了与 协作对象的自动装配 中描述的相同功能,但具有更细粒度的控制和更广泛的应用性。此外,Spring 还支持 JSR-250 注解,如 @PostConstruct@PreDestroy,以及支持包含在 jakarta.inject 包中的 JSR-330(Java 的依赖注入)注解,如 @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,它只会检查您的控制器中的 @Autowired bean,而不会检查您的服务。有关更多信息,请参阅 DispatcherServletspring-doc.cadn.net.cn