对于最新的稳定版本,请使用 Spring Framework 6.2.0! |
基于注解的容器配置
XML 设置的替代方案由基于 annotation 的配置提供,它依赖于
在字节码元数据上,用于连接组件而不是 XML 声明。而不是
使用 XML 来描述 Bean 连接,开发人员将配置移动到
组件类本身,方法是在相关类、方法或字段上使用注释
声明。如示例:AutowiredAnnotationBeanPostProcessor
,使用BeanPostProcessor
与 annotation 结合使用是扩展
Spring IoC 容器。例如,@Autowired
annotation 提供的功能与 Autowiring Collaborators 中描述的功能相同,但
具有更精细的控制和更广泛的适用性。此外,Spring 还提供
支持 JSR-250 注解,例如@PostConstruct
和@PreDestroy
以及
支持 JSR-330(Java 的依赖注入)注解,这些注解包含在jakarta.inject
软件包,例如@Inject
和@Named
.有关这些注释的详细信息
可以在相关部分找到。
注释注入在 XML 注入之前执行。因此,XML 配置 覆盖通过这两种方法连接的属性的注释。 |
与往常一样,您可以将后处理器注册为单独的 bean 定义,但是它们
也可以通过在基于 XML 的 Spring 中包含以下标记来隐式注册
配置(请注意,其中包含了context
namespace) 的 URL:
<?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/>
元素隐式注册以下后处理器:
|