阅读 835

spring中 initMethod,@PostConstruct,InitializingBean 初始化的顺序

  • 背景

最近项目中有地方要用到bean的初始化,就顺便研究了一下几种初始化的区别

  • 对比方式

  • @PostConstruct

  • InitializingBean#afterPropertiesSet

  • @Bean(initMethod = "initUserFactory")

  • 相关代码

public class DefaultUserFactory implements UserFactory , InitializingBean {

    @PostConstruct
    public void init(){
        System.out.println("PostConstruct:DefaultUserFactory 初始化");
    }

    public void initUserFactory(){
        System.out.println("自定义:DefaultUserFactory 初始化");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("InitializingBean#afterPropertiesSet: DefaultUserFactory 初始化");
    }

}
复制代码
@Configuration
public class BeanInitizlizationDemo {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext =new AnnotationConfigApplicationContext();
        //注册Configuration 配置类
        applicationContext.register(BeanInitizlizationDemo.class);
        //启动spring 应用上下文
        applicationContext.refresh();
        // 非延迟初始化在 spring 应用上下文启动完成后,被初始化
        System.out.println("spring 应用上下文已启动");
        //依赖查找
        UserFactory userFactory = applicationContext.getBean(UserFactory.class);
        System.out.println(userFactory);
        //关闭spring应用上下文
        System.out.println("spring 应用上下文准备关闭.....");
        //说明spring 中bean的销毁是在close 方法中进行的
        applicationContext.close();
        System.out.println("spring 应用上下文已经关闭");
    }
    @Bean(initMethod = "initUserFactory")
    public UserFactory userFactory(){
        return new DefaultUserFactory();
    }
}
复制代码

执行效果:

image.png

  • 结果

@PostConstruct > InitializingBean > initMethod

文章分类
后端