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

转载于:https://my.oschina.net/u/1251536/blog/1649340

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值