基於註解的容器配置
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/>` 元素隱式註冊以下後處理器
`<context:annotation-config/>` 僅在定義它的同一個應用程式 Context 中尋找 Bean 上的註解。這表示,如果您將 ` |