基於註解的容器配置
Spring 提供對基於註解的全面支援,透過在相關類、方法或欄位宣告上使用註解,在元件類本身的元資料上進行操作。正如示例:AutowiredAnnotationBeanPostProcessor
中提到的,Spring 結合註解使用 BeanPostProcessors
,使核心 IoC 容器感知到特定的註解。
例如,@Autowired
註解提供了與協作物件的自動裝配 中描述的相同功能,但具有更細粒度的控制和更廣泛的適用性。此外,Spring 支援 JSR-250 註解,例如 @PostConstruct
和 @PreDestroy
,以及支援 jakarta.inject
包中包含的 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/>
元素隱式註冊以下後處理器:
|