Spring Bean初始化和常用的接口类

Spring Bean初始化的两种方式:

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

注意:

  1. 实现InitializingBean接口是直接调用afterPropertiesSet方法,比通过反射调用init-method指定的方法效率相对来说要高点。但是init-method方式消除了对spring的依赖
  2. 如果调用afterPropertiesSet方法时出错,则不调用init-method指定的方法。
  3. 如果两种方式都配置定义了,afterPropertiesSet()先于init-method执行

Spring常用接口和类

  • ApplicationContextAware接口

如果一个类需要获取ApplicationContext实例时,可以让该类实现ApplicationContextAware接口:

public class Test implements ApplicationContextAware {
    private ApplicationContext applicationContext;
    
    public void setApplicationContext(ApplicationContext context) throws Exception {
        this.applicationContext = context;
    }
        
}
  • BeanNameAware接口 当Bean需要获取自身在容器中的id/name时,可以实现BeanNameAware接口

  • InitializingBean接口 当需要在Bean的全部属性设置成功后做些特殊处理,可以让该Bean实现InitializingBean接口。效果等同于bean的init-method属性的使用或者@PostConstruct注解

执行顺序:先执行InitializingBean接口中定义的afterPropertiesSet()方法,后执行init-method或者@PostConstruct注解的方法

  • DisposableBean接口 当需要在Bean销毁前做些特殊处理,可以让该Bean实现DisposableBean接口。效果等同于@PreDestroy注解或者destroy-method引用的方法。

执行顺序:先注解,后DisposableBean接口定义的方法,最后执行destroy-method引用的方法。

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" />

猜你喜欢

转载自my.oschina.net/u/1251536/blog/1649340