基于注解的容器配置

Spring 提供对基于注解的全面支持,通过在相关类、方法或字段声明上使用注解,在组件类本身的元数据上进行操作。正如示例:AutowiredAnnotationBeanPostProcessor 中提到的,Spring 结合注解使用 BeanPostProcessors,使核心 IoC 容器感知到特定的注解。

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

注解注入在外部属性注入之前执行。因此,当通过混合方式进行装配时,外部配置(例如 XML 指定的 Bean 属性)会有效地覆盖属性上的注解。

从技术上讲,你可以将后处理器注册为独立的 Bean 定义,但它们已经在 AnnotationConfigApplicationContext 中隐式注册。

在基于 XML 的 Spring 设置中,你可以包含以下配置标签来启用与基于注解的配置混合使用:

<?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/> 元素隐式注册以下后处理器:

<context:annotation-config/> 只查找在其自身定义的同一应用上下文中的 Bean 上的注解。这意味着,如果你在 DispatcherServletWebApplicationContext 中放置 <context:annotation-config/>,它只会检查控制器中的 @Autowired Bean,而不会检查服务中的 Bean。更多信息请参见DispatcherServlet