Spring中的Bean的作用域
Spring 4.3中为Bean的实例定义了7种作用域。
singleton作用域测试
在项目中,创建一个包,包中创建一个Scope类,该类不需要写任何方法。然后在该包中创建一个配置文件beans4.xml。最后在包中创建一个测试类ScopeTest,来测试singleton作用域。
/*beans4.xml配置文件内容*/
<bean id="scope" class="my.scope.Scope" scope="singleton"/>
/*ScopeTest.java测试类内容*/
package my.scope;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class ScopeTest{
public static void main(String[] args){
//定义配置文件路径
String xmlPath = “my/scope/beans4.xml”;
//加载配置文件
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
//输出获得实例
System.out.println(applicationContext.getBean("scope"));
System.out.println(applicationContext.getBean("scope"));
}
}
/*执行后,控制台结果为
my.scope.Scope@e9a892
my.scope.Scope@e9a892
两次结果相同,说明Spring容器只创建了一个Scope类的实例。
当beans4.xml文件中不设置 scope="singleton"时,也可以,因为Spring默认作用域为singleton
*/
prototype作用域
对需要保持会话状态的Bean应使用prototype作用域。在使用prototype作用域时,spring容器会为每个Bean请求都创建一个新的实例。
/*beans4.xml配置文件内容*/
<bean id="scope" class="my.scope.Scope" scope="prototype"/>
/*ScopeTest.java测试类内容*/
package my.scope;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class ScopeTest{
public static void main(String[] args){
//定义配置文件路径
String xmlPath = “my/scope/beans4.xml”;
//加载配置文件
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
//输出获得实例
System.out.println(applicationContext.getBean("scope"));
System.out.println(applicationContext.getBean("scope"));
}
}
/*执行后,控制台结果为
my.scope.Scope@fbd816
my.scope.Scope@2bcfcb
两次结果不相同,说明Spring容器只创建了两个Scope类的实例。
*/
注意:此时当beans4.xml文件中不设置 scope="singleton"时,不可以,因为Spring默认作用域为singleton,而并非prototype。
