Spring有三对初始化和销毁方法
- 通过@Bean注解指定initMethod和destroyMethod
- 实现InitializingBean和DisposableBean接口
- 使用@PostContruct和@PreDestroy
定义一个Car类
public class Car implements InitializingBean, DisposableBean {public Car() {System.out.println("car constructor");}@PostConstructpublic void postConstruct(){System.out.println("postConstruct");}@Overridepublic void afterPropertiesSet() throws Exception {System.out.println("InitializingBean afterPropertiesSet");}public void initMethod(){System.out.println("initMethod");}@PreDestroypublic void preDestroy(){System.out.println("preDestroy");}@Overridepublic void destroy(){System.out.println("DisposableBean destroy");}public void destroyMethod(){System.out.println("destroyMethod");}}定义配置类,并注入@Configurationpublic class MyConfigOfLifeCycle {@Bean(initMethod = "initMethod",destroyMethod = "destroyMethod")public Car car(){return new Car();}}测试@Testpublic void test04(){AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfigOfLifeCycle.class);System.out.println("容器创建完成");Object car = context.getBean("car");context.close();}执行结果【spring中bean是线程安全的吗 Spring中Bean初始化和销毁方法执行的优先级】car constructorpostConstructInitializingBean afterPropertiesSetinitMethod容器创建完成preDestroyDisposableBean destroydestroyMethod结论优先级:@PostConstruct > InitializingBean > 通过@Bean指定- 春季老年人吃什么养肝?土豆、米饭换着吃
- 三八妇女节节日祝福分享 三八妇女节节日语录
- 老人谨慎!选好你的“第三只脚”
- 校方进行了深刻的反思 青岛一大学生坠亡校方整改校规
- 脸皮厚的人长寿!有这特征的老人最长寿
- 长寿秘诀:记住这10大妙招 100%增寿
- 春季老年人心血管病高发 3条保命要诀
- 眼睛花不花要看四十八 老年人怎样延缓老花眼
- 香槟然能防治老年痴呆症? 一天三杯它人到90不痴呆
- 老人手抖的原因 为什么老人手会抖
