bean的作用域
用于确定Spring建立bean執行個體的個數
預設為singleton
可以用scope進行配置
scope取值

我們常用的:
singleton:單例模式(servlet)
prototype:多例,即執行一次getBean便獲得一個執行個體.(struct-action)
測試
測試流程
Users類
xml配置
junit測試
修改xml檔案bean的scope
junit
singleton
Users類
package com.scx.scope.test;
public class Users {
private Integer uid;
private String username;
private Integer age;
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
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="UsersId" class="com.scx.scope.test.Users" scope="singleton"></bean>
</beans>
junit測試
package com.scx.scope.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
@org.junit.Test
public void testScope() {
String xmlPath = "com/scx/scope/test/applicationContext.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
xmlPath);
Users user1 = applicationContext.getBean("UsersId", Users.class);
Users user2 = applicationContext.getBean("UsersId", Users.class);
System.out.println(user1);
System.out.println(user2);
System.out.println(user1==user2);
運作結果
兩次輸出的結果一樣 ,為單例模式
prototype
修改xml檔案bean的scope為prototype
<bean id="UsersId" class="com.scx.scope.test.Users" scope="prototype"></bean>
運作結果: