经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Spring » 查看文章
spring?bean标签中的init-method和destroy-method详解
来源:jb51  时间:2023/4/17 9:15:48  对本文有异议

1 背景介绍

在很多项目中,经常在xml配置文件中看到init-method 或者 destroy-method 。因此整理收集下,方便以后参考和学习。可以使用 init-method 和 destroy-method 在bean 配置文件属性用于在bean初始化和销毁某些动作时。这是用来替代 InitializingBean和DisposableBean接口。

init-method 用于指定bean的初始化方法。 spring 容器会帮我们实例化对象,实例化对象之后,spring就会查找我们是否配置了init-method。如果在标签配置了init-method,spring就会调用我们配置的init-method 方法,进行bean的初始化。需要注意的是,构建方法先执行,执行完后就会执行 init-method 。

2 init-method

xml配置

  1. <bean id="testService" class="com.test.TestService" init-method="myInit" destroy-method="myDestroy">
  2. </bean>
  1. public class TestService {
  2.  
  3. public TestService(){
  4. System.out.println("实例化:TestService");
  5. }
  6.  
  7. public void myInit(){
  8. System.out.println("初始化:TestService");
  9. }
  10.  
  11. public void myDestroy(){
  12. System.out.println("销毁:TestService");
  13. }
  14. }

测试

  1. public class App
  2. {
  3. public static void main( String[] args )
  4. {
  5. ConfigurableApplicationContext context =
  6. new ClassPathXmlApplicationContext(new String[] {"applicationContext.xml"});
  7. TestService cust = (CustomerService)context.getBean("testService");
  8. System.out.println("hhhhh");
  9. //context.close();
  10. }
  11. }

输出:

实例化:TestService
初始化:TestService
hhhhh

3 destroy-method

  1. public class App
  2. {
  3. public static void main( String[] args )
  4. {
  5. ConfigurableApplicationContext context =
  6. new ClassPathXmlApplicationContext(new String[] {"applicationContext.xml"});
  7. TestService cust = (CustomerService)context.getBean("testService");
  8. System.out.println("hhhhh");
  9. context.close();
  10. }
  11. }

spring上下文关闭时候,才会进行销毁。

输出:

实例化:TestService
初始化:TestService
hhhhh
销毁:TestService

4 总结

建议使用init-method 和 destroy-methodbean 在Bena配置文件,而不是执行 InitializingBean 和 DisposableBean 接口,也会造成不必要的耦合代码在Spring。

到此这篇关于spring bean标签中的init-method和destroy-method的文章就介绍到这了,更多相关spring  init-method和destroy-method内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持w3xue!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号