1 简介

很多时间当一个Bean被创建出来后,我们希望做一些初始化操作,如初始化数据、缓存预热等。有以下三种方法:

  • 初始化方法initMethod
  • 注解@PostConstruct
  • InitializingBeanafterPropertiesSet方法

2 三种方法实现

先准备一个类用于测试,代码如下:

public class BeanLifeCheck implements InitializingBean {
    private static final Logger logger = LoggerFactory.getLogger(BeanLifeCheck.class);

    @Value("${spring.application.name}")
    private String applicationName;

    public BeanLifeCheck() {
        logger.info("BeanLifeCheck: Construct " + applicationName);
    }

    public void initMethod() {
        logger.info("BeanLifeCheck: initMethod " + applicationName);
    }

    @PostConstruct
    public void postConstruct() {
        logger.info("BeanLifeCheck: postConstruct " + applicationName);
    }

    @PreDestroy
    public void preDestroy() {
        logger.info("BeanLifeCheck: preDestroy " + applicationName);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        logger.info("BeanLifeCheck: afterPropertiesSet " + applicationName);
    }
}

2.1 初始化方法initMethod

这个以前是通过xml配置文件来定义的,现在可以直接定义在@Bean注解上,如下:

@Bean(initMethod = "initMethod")
public BeanLifeCheck beanLifeCheck() {
  return new BeanLifeCheck();
}

2.2 注解@PostConstruct

直接在方法上加注解即可:

@PostConstruct
public void postConstruct() {
  logger.info("BeanLifeCheck: postConstruct " + applicationName);
}

2.3 InitializingBean的afterPropertiesSet方法

需要类实现接口InitializingBean,如下:

@Override
public void afterPropertiesSet() throws Exception {
  logger.info("BeanLifeCheck: afterPropertiesSet " + applicationName);
}

3 总结

运行后的执行日志及顺序如下:

2021-02-06 17:44:52.377: BeanLifeCheck: Construct null
2021-02-06 17:44:52.379: BeanLifeCheck: postConstruct Springboot-Common
2021-02-06 17:44:52.379: BeanLifeCheck: afterPropertiesSet Springboot-Common
2021-02-06 17:44:52.379: BeanLifeCheck: initMethod Springboot-Common
2021-02-06 17:45:10.347: BeanLifeCheck: preDestroy Springboot-Common

三种方法感觉区别不大,用哪个就看习惯了。

代码请查看:https://github.com/LarryDpk/pkslow-samples


欢迎关注微信公众号<南瓜慢说>,将持续为你更新...

Bean初始化操作initMethod、@PostConstruct和InitializingBean-LMLPHP

多读书,多分享;多写作,多整理。

06-28 12:34