基於註解的容器配置

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/> 僅查詢在其定義的同一應用程式上下文中 bean 上的註解。這意味著,如果您將 <context:annotation-config/> 放在 DispatcherServletWebApplicationContext 中,它將只檢查控制器中的 @Autowired bean,而不檢查服務中的。有關更多資訊,請參閱DispatcherServlet

© . This site is unofficial and not affiliated with VMware.