欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 前端技术 > javascript >内容正文

javascript

【Spring注解系列08】@PostConstruct与@PreDestroy

发布时间:2025/3/20 javascript 45 豆豆
生活随笔 收集整理的这篇文章主要介绍了 【Spring注解系列08】@PostConstruct与@PreDestroy 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

1.@PostConstruct与@PreDestroy

@PostConstruct:在bean创建完成并且属性赋值完成;来执行初始化方法 @PreDestroy:在容器销毁bean之前通知我们进行清理工作

2.实例

@Service public class PersonService {@PostConstructpublic void post(){System.out.println("PersonService ... PostConstruct");}@PreDestroypublic void pre(){System.out.println("PersonService ... PreDestroy");} }@Configuration @ComponentScan(value = {"com.java.service"}) public class PostConstructConfig { }//测试类 public class PostConstructTest {public static void main(String[] args) {AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(PostConstructConfig.class);System.out.println("applicationContext ..... 初始化结束");//只有bean从容器中移除时,才会调用preDestroy来通知System.out.println("applicationContext ..... 准备关闭");applicationContext.close();System.out.println("applicationContext ..... 已关闭");} }运行结果:PersonService ... PostConstruct applicationContext ..... 初始化结束 applicationContext ..... 准备关闭 PersonService ... PreDestroy applicationContext ..... 已关闭

 

总结

以上是生活随笔为你收集整理的【Spring注解系列08】@PostConstruct与@PreDestroy的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。