小记--InitializingBean子类afterPropertiesSet()方法不执行

InitializingBean与Spring 懒加载


在之前的文章 Java中多If else优化 (三)----工厂+策略模式优化中提到InitializingBean接口,继承该接口的Bean在初始化完成后,会执行重写的afterPropertiesSet()方法,但在新项目中发现直到项目启动完成,实现类的afterPropertiesSet()方法也没有被执行。


public interface InitializingBean {
    /**
      * Invoked by a BeanFactory after it has set all bean properties supplied
      * (and satisfied BeanFactoryAware and ApplicationContextAware).
      * <p>This method allows the bean instance to perform initialization only
      * possible when all bean properties have been set and to throw an
      * exception in the event of misconfiguration.
      * @throws Exception in the event of misconfiguration (such
      * as failure to set an essential property) or if initialization fails.
      */
     void afterPropertiesSet() throws Exception;
 }

该方法会在Bean的所有属性初始化完成后调用,但是当Spring 配置bean为延迟初始化,即懒加载(lazy-init),类对象如果不被使用,则不会实例化该类对象,将导致InitializingBean子类的afterPropertiesSet()的方法不能执行。若需要Spring容器启动时就初始化并调用afterPropertiesSet()方法,可在类上通过注解@Lazy(value=false) (org.springframework.context.annotation.Lazy)配置为非延迟加载即可。


import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.Lazy; 
/**
 * @Description:
 * @Author: 
 * @CreateDate: 
 */
@Lazy(value=false)
public class InitializingBeanTest implements InitializingBean {
    
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("InitializingBeanTest......");
    }    
}
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值