Annotation-based Container Configuration
Spring 提供对基于注解的配置的全面支持,通过使用对相关类、方法或字段声明的注解来对组件类本身中的元数据进行操作。正如 "@48" 中提到的,Spring 连同注解一起使用 "@47",以使核心 IOC 容器识别特定注解。
Spring provides comprehensive support for annotation-based configuration, operating on
metadata in the component class itself by using annotations on the relevant class,
method, or field declaration. As mentioned in
Example: The AutowiredAnnotationBeanPostProcessor
,
Spring uses BeanPostProcessors
in conjunction with annotations to make the core IOC
container aware of specific annotations.
例如,@Autowired
注释提供了与 Autowiring Collaborators 中描述的相同功能,但是具有更细粒度的控制和更广泛的适用性。此外,Spring 支持 JSR-250 注释(例如 @PostConstruct
和 @PreDestroy
),以及支持 JSR-330(Java 的依赖注入)注释(如 jakarta.inject
包中包含的 @Inject
和 @Named
)。有关这些注释的详细信息,请参阅 relevant section。
For example, the @Autowired
annotation provides the same capabilities as described in
Autowiring Collaborators but
with more fine-grained control and wider applicability. In addition, Spring provides
support for JSR-250 annotations, such as @PostConstruct
and @PreDestroy
, as well as
support for JSR-330 (Dependency Injection for Java) annotations contained in the
jakarta.inject
package such as @Inject
and @Named
. Details about those annotations
can be found in the relevant section.
注解注入在外部属性注入之前进行。因此,外部配置(例如 XML 指定的 Bean 属性)实际上覆盖了通过混合方法连接时的属性注解。 Annotation injection is performed before external property injection. Thus, external configuration (e.g. XML-specified bean properties) effectively overrides the annotations for properties when wired through mixed approaches. |
从技术上讲,可以将后置处理器注册为单个 Bean 定义,但它们已隐式注册在 AnnotationConfigApplicationContext
中。
Technically, you can register the post-processors as individual bean definitions, but they
are implicitly registered in an AnnotationConfigApplicationContext
already.
在基于 XML 的 Spring 设置中,可以包含以下配置标记,以启用与基于注解的配置的混合和匹配:
In an XML-based Spring setup, you may include the following configuration tag to enable mixing and matching with annotation-based configuration:
<?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/>
元素隐式注册了以下后置处理器:
The <context:annotation-config/>
element implicitly registers the following post-processors:
|