这篇文章主要介绍了spring bean标签中的init-method和destroy-method怎么使用的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇spring bean标签中的ini
这篇文章主要介绍了spring bean标签中的init-method和destroy-method怎么使用的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇spring bean标签中的init-method和destroy-method怎么使用文章都会有所收获,下面我们一起来看看吧。
在很多项目中,经常在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 。
xml配置
<bean id="testService" class="com.test.TestService" init-method="myInit" destroy-method="myDestroy"> </bean>
public class TestService { public TestService(){ System.out.println("实例化:TestService"); } public void myInit(){ System.out.println("初始化:TestService"); } public void myDestroy(){ System.out.println("销毁:TestService"); }}
public class App { public static void main( String[] args ) { ConfigurableApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"applicationContext.xml"}); TestService cust = (CustomerService)context.getBean("testService"); System.out.println("hhhhh"); //context.close(); }}
输出:
实例化:TestService
初始化:TestService
hhhhh
public class App { public static void main( String[] args ) { ConfigurableApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"applicationContext.xml"}); TestService cust = (CustomerService)context.getBean("testService"); System.out.println("hhhhh"); context.close(); }}
spring上下文关闭时候,才会进行销毁。
输出:
实例化:TestService
初始化:TestService
hhhhh
销毁:TestService
关于“spring bean标签中的init-method和destroy-method怎么使用”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“spring bean标签中的init-method和destroy-method怎么使用”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注编程网精选频道。
--结束END--
本文标题: spring bean标签中的init-method和destroy-method怎么使用
本文链接: https://www.lsjlt.com/news/357736.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-05-22
2024-05-22
2024-05-22
2024-05-22
2024-05-22
2024-05-22
2024-05-22
2024-05-21
2024-05-21
2024-05-21
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0