Spring(四)JavaBean作用范围的配置及生命周期

来源:互联网 发布:中国汽车发展历史 知乎 编辑:程序博客网 时间:2024/04/28 08:47

Bean的作用范围有几种:

  • singleton  在每个Spring Ioc容器中一个Bean定义只有一个对象实例。默认情况下会在容器启动时初始化Bean,但我们可以指定Bean节点的lazy-init="true"来延迟初始化Bean,这样只有第一次获取Bean才会初始化Bean。如:
    <bean id=".." class=".." lazy-init="true"/>
    如果想对所有Bean都应用延迟初始化,可以在根节点beans设置default-lazy-init="true",如下:
    <beans default-lazy-init="true">
  • prototype  每次从容器获取bean都是新的对象
还有三种是应用在web project中的:requestsessionglobal session
package test.spring.jnit;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import test.spring.service.impl.PersonServiceBean;public class BeanScopeTest {@Testpublic void testScope() {ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");// -------------------------------------------------PersonServiceBean personServiceBean1 = (PersonServiceBean) applicationContext.getBean("personService");PersonServiceBean personServiceBean2 = (PersonServiceBean) applicationContext.getBean("personService");System.out.println(personServiceBean1 == personServiceBean2);}}
按之前的配置这块代码返回true,但如果改变PersonServiceBean的作用范围
<bean id="personService" class="test.spring.service.impl.PersonServiceBean"scope="prototype"></bean>
就会返回false

<bean id="personService" class="test.spring.service.impl.PersonServiceBean"lazy-init="false" init-method="init" destroy-method="destroy"></bean>
bean的初始化在实例化之后,而销毁即释放资源在Spring容器关闭后
package test.spring.service.impl;import test.spring.service.PersonService;public class PersonServiceBean implements PersonService {public void init(){System.out.println("初始化");}public PersonServiceBean(){System.out.println("现在实例化");}@Overridepublic void save(){System.out.println("=============");}public void destroy() {System.out.println("释放资源");}}

package test.spring.jnit;import org.junit.Test;import org.springframework.context.support.AbstractApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class BeanScopeTest {@Testpublic void testScope() {// ApplicationContext applicationContext = new// ClassPathXmlApplicationContext(// "beans.xml");// 如果scope="singleton",现在对bean实例化// System.out.println("-------------------------------");/* * 如果scope="prototype",现在对bean实例化。 * 如果scope="singleton",通过设置lazy-init="true"延迟实 例化的时间,bean也在此时实例化。 */// PersonServiceBean personServiceBean1 = (PersonServiceBean)// applicationContext// .getBean("personService");// PersonServiceBean personServiceBean2 = (PersonServiceBean)// applicationContext// .getBean("personService");//// System.out.println(personServiceBean1 == personServiceBean2);//// 返回trueAbstractApplicationContext abstractApplicationContext = new ClassPathXmlApplicationContext("beans.xml");abstractApplicationContext.close();}}


0 0
原创粉丝点击