Spring Bean初始化和經常使用的接口類

Spring Bean初始化的兩種方式:

  • 實現InitializingBean接口的afterPropertiesSet方法
  • 配置文件中指定init-method或者使用@PostConstruct註解

注意:spring

  1. 實現InitializingBean接口是直接調用afterPropertiesSet方法,比經過反射調用init-method指定的方法效率相對來講要高點。可是init-method方式消除了對spring的依賴
  2. 若是調用afterPropertiesSet方法時出錯,則不調用init-method指定的方法。
  3. 若是兩種方式都配置定義了,afterPropertiesSet()先於init-method執行

Spring經常使用接口和類

  • ApplicationContextAware接口

若是一個類須要獲取ApplicationContext實例時,能夠讓該類實現ApplicationContextAware接口:apache

public class Test implements ApplicationContextAware {
    private ApplicationContext applicationContext;
    
    public void setApplicationContext(ApplicationContext context) throws Exception {
        this.applicationContext = context;
    }
        
}
  • BeanNameAware接口 當Bean須要獲取自身在容器中的id/name時,能夠實現BeanNameAware接口app

  • InitializingBean接口 當須要在Bean的所有屬性設置成功後作些特殊處理,能夠讓該Bean實現InitializingBean接口。效果等同於bean的init-method屬性的使用或者@PostConstruct註解this

執行順序:先執行InitializingBean接口中定義的afterPropertiesSet()方法,後執行init-method或者@PostConstruct註解的方法url

  • DisposableBean接口 當須要在Bean銷燬前作些特殊處理,能夠讓該Bean實現DisposableBean接口。效果等同於@PreDestroy註解或者destroy-method引用的方法。

執行順序:先註解,後DisposableBean接口定義的方法,最後執行destroy-method引用的方法。spa

Spring內置的實現類

  • PropertyPlaceholderConfigurer類 用於讀取Java屬性文件中的屬性,而後插入到BeanFactory的定義中
<bean id="propertyPlaceholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>jdbc.properties</value>
        </list>
    </property>
</bean>

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="${jdbc.className}" />
    <property name="url" value="${jdbc.url}" />
    <property name="username" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />
</bean>
PropertyPlaceholderConfigurer另外一種精簡配置方式(context命名空間)
<context:property-placeholder location="classpath:jdbc.properties, classpath:mails.properties" />
相關文章
相關標籤/搜索