您的位置:首页 > 编程语言 > Java开发

Spring 实例化bean的初始化方法和销毁方法 init-method destroy-method

2013-04-22 20:57 786 查看
Spring版本 2.5首先我们应该知道:[b][b]一、[/b]spring Bean的作用域:scope=singleton(默认,单例,生成一个实例)[/b][b]二、spring Bean的作用域:scope=prototype(多线程, 生成多个实例)[/b][b]三、单例模式,默认在程序初始化的时候实例化([b][b][b][b][b][b][b][b][b][b][b][b][b][b][b][b][b][b][b][b]lazy-init="false"[/b][/b][/b][/b][/b][/b][/b][/b][/b][/b][/b][/b][/b][/b][/b][/b][/b][/b][/b])[/b][/b][b]四、[b][b]prototype,getBean的时候才是实例化[/b][/b][/b][b][b][b]五、lazy-init 只对单例模式起作用,对 [b][b][b][b]prototype 不起作用(因为 [b][b][b][b] [b][b][b][b]prototype 默认就不是程序初始化的时候实例化的[/b][/b][/b][/b][/b][/b][/b])[/b][/b][/b][/b][/b][/b][/b][/b][b]1. 情况一:[/b]
<bean id="personService6" class="com.yokoboy.service.impl.PersonServiceBean"  init-method="init" destroy-method="destory" />
AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");

PersonService singleton1 = (PersonService) ctx.getBean("personService6");
PersonService singleton2 = (PersonService) ctx.getBean("personService6");
System.out.println(singleton1==singleton2);

ctx.registerShutdownHook();
输出情况:

    我被实例化了
    初始化    true
    开闭打开的资源说明: 1. 这个bean 是单例的,   2. 这个bean不是懒加载
[b]2. 情况二[/b]
<bean id="personService6" class="com.yokoboy.service.impl.PersonServiceBean"   init-method="init" destroy-method="destory" scope="prototype" />
AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");PersonService singleton1 = (PersonService) ctx.getBean("personService6");
PersonService singleton2 = (PersonService) ctx.getBean("personService6");
System.out.println(singleton1==singleton2);
ctx.registerShutdownHook();

输出情况:
  我被实例化了
  初始化
  我被实例化了
  初始化
  false
说明:

destroy-method="destory"只有在单例模式下再有作用。

[b]情况三:[/b]
<bean id="personService6" class="com.yokoboy.service.impl.PersonServiceBean"   init-method="init" destroy-method="destory" />
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
输出:  我被实例化了
  初始化
说明:
  程序并不知道什么时候调用 destory 方法。

最重要的是:
  在CS应用程序中,destroy-method="destory" 这个配置基本上没有作用,因为 摧毁方法是由容器调用的,在CS应用程序中,只有程序员自己调用。
再有,当scope是prototype的时候,对象的生存周期 Spring就不管了。只有在tomcat或者容器关闭的时候,由tomcat调用。


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐