跳到主要内容
版本:7.0.3

基于注释的容器配置

Hunyuan 7b 中英对照 Annotation-based Container Configuration

Spring提供了基于注解的配置的全面支持,通过在相关类、方法或字段声明上使用注解来操作组件类本身的元数据。如示例:AutowiredAnnotationBeanPostProcessor中提到的,Spring结合使用BeanPostProcessors和注解,让核心的IOC容器能够识别特定的注解。

例如,@Autowired 注解提供了与 Autowiring Collaborators 中描述的相同功能,但具有更细粒度的控制和更广泛的适用性。此外,Spring 还支持 JSR-250 注解,如 @PostConstruct@PreDestroy,同时也支持包含在 jakartainject 包中的 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/> 仅在其定义的同一应用程序上下文中查找注解。这意味着,如果您在 DispatcherServletWebApplicationContext 中添加了 <context:annotation-config/>,它只会检查控制器中的 @Autowired 注解,而不会检查服务中的注解。有关更多信息,请参阅 DispatcherServlet

部分总结

📄️ 使用 @PostConstruct 和 @PreDestroy

CommonAnnotationBeanPostProcessor不仅能够识别@Resource注解,还能识别JSR-250生命周期注解:jakarta.annotation.PostConstruct和jakarta.annotation.PreDestroy。这一功能是从Spring 2.5开始引入的,它为初始化回调和销毁回调中描述的生命周期回调机制提供了一种替代方案。只要CommonAnnotationBeanPostProcessor在Spring ApplicationContext中进行了注册,那么带有这些注解的方法就会在生命周期的同一阶段被调用,与相应的Spring生命周期接口方法或明确定义的回调方法执行的时间点相同。在以下示例中,缓存会在初始化时被预先填充,在销毁时被清除: