小记--InitializingBean子类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......");
    }    
}
经验分享 程序员 微信小程序 职场和发展