此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Framework 6.2.0spring-doc.cadn.net.cn

基于注解的容器配置

Spring 为基于 Comments 的配置提供了全面的支持,在 metadata 在组件类本身中使用 Comments, method 或字段声明。如示例:AutowiredAnnotationBeanPostProcessor, Spring 用途BeanPostProcessors与 annotation 结合使用,以使核心 IOC 容器识别特定注释。spring-doc.cadn.net.cn

例如,@Autowiredannotation 提供的功能与 Autowiring Collaborators 中描述的功能相同,但 具有更精细的控制和更广泛的适用性。此外,Spring 还提供 支持 JSR-250 注解,例如@PostConstruct@PreDestroy以及 支持 JSR-330(Java 的依赖注入)注解,这些注解包含在jakarta.inject软件包,例如@Inject@Named.有关这些注释的详细信息 可以在相关部分找到。spring-doc.cadn.net.cn

注释注入在外部属性注入之前执行。因此,外部 配置(例如,XML 指定的 bean 属性)有效地覆盖了注释 对于通过混合方法连接的属性。spring-doc.cadn.net.cn

从技术上讲,你可以将后处理器注册为单独的 bean 定义,但是它们 隐式注册在AnnotationConfigApplicationContext已经。spring-doc.cadn.net.cn

在基于 XML 的 Spring 设置中,您可以包含以下配置标记以启用 与基于 Comments 的配置进行混合和匹配: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, 它只检查@Autowiredbean 在你的控制器中,而不是你的服务中。有关更多信息,请参阅 DispatcherServletspring-doc.cadn.net.cn