标签:
Bean的作用范围有几种:
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 {
@Test
public 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>
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("现在实例化");
}
@Override
public 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 {
@Test
public 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);//
// 返回true
AbstractApplicationContext abstractApplicationContext = new ClassPathXmlApplicationContext(
"beans.xml");
abstractApplicationContext.close();
}
}
版权声明:本文为博主原创文章,未经博主允许不得转载。如需转载,请注明出处:http://blog.csdn.net/lindonglian
标签:
原文地址:http://blog.csdn.net/lindonglian/article/details/47018939