一、bean的范围
与HelloWorld项目一样创建一个普通的java项目,创建一个bean类Person,MainTest测试类,spring.xml配置文件(后面有完整的代码)。
先来看MainTest的代码,主要部分是通过getBean两次获取Person的实例,然后打印两个引用的“==”结果。
再来看配置文件,当还没有scope=“prototype”的时候打印结果为true,即两个引用指向的是一个对象;当使用了prototype时,打印结果为false。表示是不同的两个对象,这就是scope的prototype取值的作用每次都返回一个新的实例。
关于scope的取值见下表。我们这里只讨论了prototype这一个属性。sigleton属性在项目中也可以测试,其他两个则需要在web项目中才可测试。
属性值 | 作用 |
sigleton | 在springIOC容器中仅存一个实例,Bean以单例存在。 |
prototype | 每次通过容器的方法获取bean时都返回一个新实例。 |
request | http每次请求都创建一个Bean,作用于WebApplicationContext域 |
session | 同一个合同http的session共享一个Bean实例,作用于WebApplicationContext域 |
import com.escore.beans.Person;
public class MainTest {
public static void main(String[] args) {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
Person person1 = ctx.getBean(Person.class);
Person person2 = ctx.getBean(Person.class);
System.out.println(person1==person2);
ctx.close();
}
}
<bean id="person" class="com.escore.beans.Person"
scope="prototype">
<property name="name" value="scopeTest"></property>
</bean>
------------------------------------整个小案例的完整代码---------------------------
Person.java
public class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person [name=" + name + "]";
}
}
MainTest.java
import com.escore.beans.Person;
public class MainTest {
public static void main(String[] args) {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
Person person1 = ctx.getBean(Person.class);
Person person2 = ctx.getBean(Person.class);
System.out.println(person1==person2);
ctx.close();
}
}
spring.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">
<!-- scope设置bean的作用范围 -->
<bean id="person" class="com.escore.beans.Person"
scope="prototype">
<property name="name" value="scopeTest"></property>
</bean>
</beans>