<?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">
<beans>
<bean id="testBean" class="TestBean" scope="prototype">
<property name="name" value="zxk"/>
<property name="age" value="2"/>
</bean>
<bean id="aTestBean" class="ATestBean">
<property name="name" value="zxk"/>
<property name="age" value="2"/>
</bean>
</beans>
</beans>
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestBean {
private String name;
private Integer age;
TestBean(){
System.out.println("初始化。。。");
}
public Integer getAge() {
return age;
}
public String getName() {
return name;
}
public void setAge(Integer age) {
this.age = age;
}
public void setName(String name) {
this.name = name;
}
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring.xml");
TestBean testBean = (TestBean) context.getBean("testBean");
TestBean testBean2 = (TestBean) context.getBean("testBean");
System.out.println(testBean.getName());
System.out.println(testBean2.getName());
}
}
执行结果
Scope值为Singleton的只实例化了一次
而值为prototye的实例化了两次
scope名称 | 作用 |
---|---|
singleton | 单例模式,只实例化一次,多次执行getBean()但是只实例化一次 |
prototype | 原型模式,实例多次,每次在做getBean()操作的时候就会执行一次实例化 |
request | http每请求一次,就创建一个新的bean |
session | 同一个HttpSession共享同一个bean对象,不同的session使用不同的bean对象 |
application | 全局web作用域 |