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......");
}
}