发布网友 发布时间:2024-10-15 15:01
共1个回答
热心网友 时间:2024-10-30 15:20
背景最近项目中有地方要用到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
作者:董懂