首页>>后端>>Spring->Spring中initMethod,@PostConstruct,InitializingBean初始化的顺序

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

时间:2023-11-29 本站 点击:0

背景

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

对比方式

@PostConstruct

InitializingBean#afterPropertiesSet

@Bean(initMethod = "initUserFactory")

相关代码

publicclassDefaultUserFactoryimplementsUserFactory,InitializingBean{@PostConstructpublicvoidinit(){System.out.println("PostConstruct:DefaultUserFactory初始化");}publicvoidinitUserFactory(){System.out.println("自定义:DefaultUserFactory初始化");}@OverridepublicvoidafterPropertiesSet()throwsException{System.out.println("InitializingBean#afterPropertiesSet:DefaultUserFactory初始化");}}
@ConfigurationpublicclassBeanInitizlizationDemo{publicstaticvoidmain(String[]args){AnnotationConfigApplicationContextapplicationContext=newAnnotationConfigApplicationContext();//注册Configuration配置类applicationContext.register(BeanInitizlizationDemo.class);//启动spring应用上下文applicationContext.refresh();//非延迟初始化在spring应用上下文启动完成后,被初始化System.out.println("spring应用上下文已启动");//依赖查找UserFactoryuserFactory=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")publicUserFactoryuserFactory(){returnnewDefaultUserFactory();}}

执行效果:

结果

@PostConstruct > InitializingBean > initMethod


本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:/Spring/305.html