Spring有如下5个 bean 范围:
1:singleton—每次从spring container 中返回一个单例对象,不进行新对象的创建;
2:prototype—和singleton相反,每次从spring container中返回不同的对象,每次进行新对象的创建
3:request—返回一个single bean 对象 每次 HTTP request
4:session—返回一个single bean 对象 每次 HTTP session
5:globalSession—返回一个single bean 实例每次 全局 HTTP session
定义一个类:
package com.myapp.core.beanscope;
public class PersonService {
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
定义对应的xml配置文件:
<!-- bean scope test about singleton and prototype -->
<!-- change the scope in the singleton and prototype -->
<bean id="personService" class="com.myapp.core.beanscope.PersonService" scope="prototype">
</bean>
编写测试类:MainTest.java
package com.myapp.core.beanscope;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainTest {
public static void main(String[] args) {
ApplicationContext context =new ClassPathXmlApplicationContext("SpringBeans.xml");
PersonService person = (PersonService)context.getBean("personService");
person.setMessage("hello spring");
PersonService person_new = (PersonService)context.getBean("personService");
System.out.println(person.getMessage());
System.out.println(person_new.getMessage());
//explain output the same message validate the singleton scope only create a instance;
// when scope is singleton output following:
/**
* hello spring
* hello spring
*/
//the following test need to modify personServie bean's scope to prototype then see the output
//when scope is prototype output as following;
/**
* hello spring
* null
*/
}
}
当把xml中配置文件的 scope="singleton"的时候;
输出
hello spring
hello spring
证明每次从spring container中获取的是一个 对象
把xml配置文件中改为如下 scope="prototype"的时候
输出:
hello spring
null
证明每次从spring container中获取的是不同的对象,每次都创建新对象。