Spring Bean的初始化和销毁实例详解
本文实例讲述了SpringBean的初始化和销毁。分享给大家供大家参考,具体如下:
一点睛
在开发过程中,经常遇到在Bean使用之前或者之后做一些必要的操作,Spring对Bean的生命周期的操作提供了支持。
1Java配置方式:使用@Bean的initMethod和destroyMethod。
2注解方式:利用JSR-250的@PostConstruct和@PreDestroy。
二实战
1增加JSR250支持
javax.annotation jsr250-api 1.0
2使用@Bean形式的Bean
packagecom.wisely.highlight_spring4.ch2.prepost; publicclassBeanWayService{ publicvoidinit(){ System.out.println("@Bean-init-method"); } publicBeanWayService(){ super(); System.out.println("初始化构造函数-BeanWayService"); } publicvoiddestroy(){ System.out.println("@Bean-destory-method"); } }
3使用JSR250形式的Bean
packagecom.wisely.highlight_spring4.ch2.prepost; importjavax.annotation.PostConstruct; importjavax.annotation.PreDestroy; publicclassJSR250WayService{ @PostConstruct//在构造函数执行之后执行 publicvoidinit(){ System.out.println("jsr250-init-method"); } publicJSR250WayService(){ super(); System.out.println("初始化构造函数-JSR250WayService"); } @PreDestroy//在Bean销毁之前执行 publicvoiddestroy(){ System.out.println("jsr250-destory-method"); } }
4编写配置类
packagecom.wisely.highlight_spring4.ch2.prepost; importorg.springframework.context.annotation.Bean; importorg.springframework.context.annotation.ComponentScan; importorg.springframework.context.annotation.Configuration; @Configuration @ComponentScan("com.wisely.highlight_spring4.ch2.prepost") publicclassPrePostConfig{ //initMethod和destroyMethod指定BeanWayService类的 //init和destroy方法在构造函数之后、Bean销毁之前执行 @Bean(initMethod="init",destroyMethod="destroy") BeanWayServicebeanWayService(){ returnnewBeanWayService(); } @Bean JSR250WayServicejsr250WayService(){ returnnewJSR250WayService(); } }
5编写主类
packagecom.wisely.highlight_spring4.ch2.prepost; importorg.springframework.context.annotation.AnnotationConfigApplicationContext; publicclassMain{ publicstaticvoidmain(String[]args){ AnnotationConfigApplicationContextcontext= newAnnotationConfigApplicationContext(PrePostConfig.class); BeanWayServicebeanWayService=context.getBean(BeanWayService.class); JSR250WayServicejsr250WayService=context.getBean(JSR250WayService.class); context.close(); } }
三测试
八月06,20189:53:47下午org.springframework.context.annotation.AnnotationConfigApplicationContextprepareRefresh
信息:Refreshingorg.springframework.context.annotation.AnnotationConfigApplicationContext@1f17ae12:startupdate[MonAug0621:53:47CST2018];rootofcontexthierarchy
初始化构造函数-BeanWayService
@Bean-init-method
初始化构造函数-JSR250WayService
jsr250-init-method
八月06,20189:53:47下午org.springframework.context.annotation.AnnotationConfigApplicationContextdoClose
信息:Closingorg.springframework.context.annotation.AnnotationConfigApplicationContext@1f17ae12:startupdate[MonAug0621:53:47CST2018];rootofcontexthierarchy
jsr250-destory-method
@Bean-destory-method
更多关于java相关内容感兴趣的读者可查看本站专题:《Spring框架入门与进阶教程》、《Java数据结构与算法教程》、《Java操作DOM节点技巧总结》、《Java文件与目录操作技巧汇总》和《Java缓存操作技巧汇总》
希望本文所述对大家java程序设计有所帮助。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。