spring使用註解@PostConstruct的xml配置
阿新 • • 發佈:2019-01-05
Spring 2.1 添加了一個新的 context 的 Schema 名稱空間,該名稱空間對註釋驅動、屬性檔案引入、載入期織入等功能提供了便捷的配置。我們知道註釋本身是不會做任何事情的,它僅提供元資料資訊。要使元資料資訊真正起作用,必須讓負責處理這些元資料的處理器工作起來。
而我們前面所介紹的AutowiredAnnotationBeanPostProcessor和CommonAnnotationBeanPostProcessor就是處理這些註釋元資料的處理器。但是直接在 Spring 配置檔案中定義這些 Bean 顯得比較笨拙。Spring 為我們提供了一種方便的註冊這些BeanPostProcessor的方式,這就是 <context:annotation-config/>。請看下面的配置:
<?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
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:annotation-config/>
<bean id="boss" class="com.baobaotao.Boss"/>
<bean id="office" class="com.baobaotao.Office">
<property name="officeNo" value="001"/>
</bean>
<bean id="car" class="com.baobaotao.Car" scope="singleton">
<property name="brand" value=" 紅旗 CA72"/>
<property name="price" value="2000"/>
</bean>
</beans>
<context:annotationconfig/> 將隱式地向 Spring 容器註冊AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor、PersistenceAnnotationBeanPostProcessor以及equiredAnnotationBeanPostProcessor這 4 個 BeanPostProcessor。
在配置檔案中使用 context 名稱空間之前,必須在 <beans> 元素中宣告 context 名稱空間。