Bean初始化

本文详细介绍了Spring框架中Bean初始化的三种方式:实现InitializingBean接口、使用@PostConstruct注解和initMethod方法。着重讨论了它们的执行顺序:空参构造->@PostConstruct->afterPropertiesSet->initMethod。
摘要由CSDN通过智能技术生成

Bean初始化

我们很多时候在Bean初始化之后会去做一些操作,如:数据初始化缓存预热等初始化操作。Spring提供了三种方式!

  • 实现InitializingBean接口,重写afterPropertiesSet方法。
  • 使用@PostConstruct
  • 指定Bean的 initMethod 方法

执行顺序

@PostConstruct -> InitializingBean(afterPropertiesSet) -> initMethod

代码演示

InitializingBean 和 @PostConstruct:

public class SpringBootExample implements InitializingBean {

    private static SimpleDateFormat dt;
    
    public SpringBootExample() {
        System.out.println("空参构造调用");
    }

    @PostConstruct
    protected void init() {
        System.out.println("PostConstruct start init ");
        dt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        System.out.println("PostConstruct end init , dt: yyyy-MM-dd hh:mm:ss");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("afterPropertiesSet start init ");
        dt = new SimpleDateFormat("yyyy-MM-dd");
        System.out.println("afterPropertiesSet end init ,  dt: yyyy-MM-dd");
    }

    public void initMethod() {
        System.out.println("initMethod start init ");
        dt = new SimpleDateFormat("yyyy-MM-dd hh");
        System.out.println("initMethod end init , dt: yyyy-MM-dd hh");
    }

}

initMethod方法:

@Configuration
public class TestConfig {

    @Bean(initMethod = "initMethod")
    public SpringBootExample springBootExample(){
        return new SpringBootExample();
    }

}

结果显示

空参构造调用
PostConstruct start init 
PostConstruct end init , dt: yyyy-MM-dd hh:mm:ss
afterPropertiesSet start init 
afterPropertiesSet end init ,  dt: yyyy-MM-dd
initMethod start init 
initMethod end init , dt: yyyy-MM-dd hh

从结果可以清晰的看到:
Bean在初始化时先调用空参构造器进行实例化,后调用 @PostConstruct方法进行初始化,在调用afterPropertiesSet最后才是initMethod.若以上流程有一个报错,则不进行后面的方法调用。

Bean初始化参考文章

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值