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" />
相关文章
相关标签/搜索