配置Spring管理的bean的作用域

Spring管理的bean的作用域有:

1.singleton 

在每个Spring IoC容器中,一个bean定义只有一个对象实例。 
以Spring的三种实例化Bean的方式的案例为基础,我们举例说明。首先我们将Spring的配置文件——beans.xml的内容改为:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="personService" class="cn.itcast.service.impl.PersonServiceBean"></bean>

</beans>

然后再将SpringTest类的代码改为:

public class SpringTest {

    @Test
    public void test() {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); // 实例化Spring容器
        PersonService personService1 = (PersonService) ctx.getBean("personService"); // 从Spring容器取得bean
        PersonService personService2 = (PersonService) ctx.getBean("personService"); 
        System.out.println(personService1 == personService2); // 输出true,两个变量所引用的对象是同一个,证实了默认情况下这个bean交给Spring容器管理之后,这个bean是一个单实例。
    }

}

最后,测试test()方法,Eclipse的控制台输出true,说明了默认情况下bean交给Spring容器管理之后,这个bean就是一个单实例(单例模式)的,即每次调用getBean()方法,获取到的都是同一个bean实例。

2.prototype 

现在我们有了一个新的需求,那就是在客户端每次调用getBean()方法,获取到的都是一个新的bean实例,这个时候就需要用到prototype作用域了。每次从容器获取bean都是新的对象。
为了证明这一点,我们只须将Spring的配置文件——beans.xml的内容改为:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="personService" class="cn.itcast.service.impl.PersonServiceBean" scope="prototype"></bean>

</beans>

SpringTest类的代码不用改动,此时测试test()方法,Eclipse的控制台会输出false。这就已经证实了若bean的作用域置为prototype,那么每次从Spring容器获取bean都将是新的对象。

其次,还有一些不太常用的的,包括

  • request
  • session
  • global session
原文地址:https://www.cnblogs.com/zbdouble/p/9227687.html