跳到主要内容

基于注解的容器配置

ChatGPT-4o 中英对照 Annotation-based Container Configuration

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

例如,@Autowired 注解提供了与 自动装配协作者 中描述的相同功能,但具有更细粒度的控制和更广泛的适用性。此外,Spring 提供对 JSR-250 注解的支持,例如 @PostConstruct@PreDestroy,以及对 JSR-330(Java 的依赖注入)注解的支持,这些注解包含在 jakarta.inject 包中,例如 @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>
xml

<context:annotation-config/> 元素隐式注册以下后置处理器:

备注

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

章节摘要

📄️ 使用 @PostConstruct 和 @PreDestroy

CommonAnnotationBeanPostProcessor 不仅识别 @Resource 注解,还识别 JSR-250 生命周期注解:jakarta.annotation.PostConstruct 和 jakarta.annotation.PreDestroy。这些注解的支持在 Spring 2.5 中引入,提供了一种替代生命周期回调机制的方法,如初始化回调和销毁回调中所述。只要 CommonAnnotationBeanPostProcessor 在 Spring ApplicationContext 中注册,带有这些注解的方法将在生命周期的相同点被调用,就像对应的 Spring 生命周期接口方法或显式声明的回调方法一样。在以下示例中,缓存在初始化时预填充,并在销毁时清除: