iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >spring bean标签中的init-method和destroy-method详解
  • 421
分享到

spring bean标签中的init-method和destroy-method详解

Python 官方文档:入门教程 => 点击学习

摘要

目录1 背景介绍2 init-method3 destroy-method4 总结1 背景介绍 在很多项目中,经常在xml配置文件中看到init-method 或者 destroy-

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配置

    <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

3 destroy-method

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

4 总结

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

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

--结束END--

本文标题: spring bean标签中的init-method和destroy-method详解

本文链接: https://www.lsjlt.com/news/209926.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作