转自:
Spring Bean作用域简介说明
Bean作用域简介
Bean作用域指一个Bean是否为单例模式,还是每次访问新实例,或一个Session一个新实例等方式,
那么Bean作用域有哪几种呢?
下文将一一道来
作用域 |
描述 |
singleton |
在spring IoC容器仅存在一个Bean实例,Bean以单例方式存在,默认值 |
prototype |
每次从容器中调用Bean时,都返回一个新的实例,即每次调用getBean()时,相当于执行newXxxBean() |
request |
每次HTTP请求都会创建一个新的Bean,该作用域仅适用于WebApplicationContext环境 |
session |
同一个HTTP Session共享一个Bean,不同Session使用不同的Bean,仅适用于WebApplicationContext环境 |
global-session |
一般用于Portlet应用环境,该运用域仅适用于WebApplicationContext环境 |
例:
package com.java265;
public class HelloWorld {
private String message;
public void setMessage(String message) {
this.message = message;
}
public void getMessage() {
System.out.println("message : " + message);
}
}
package com.java265;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
HelloWorld objA = (HelloWorld) context.getBean("helloWorld");
objA.setMessage("对象A");
objA.getMessage();
HelloWorld objB = (HelloWorld) context.getBean("helloWorld");
objB.getMessage();
}
}
---Beans.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-3.0.xsd">
<bean id="helloWorld" class="com.java265.HelloWorld" scope="singleton"/>
</beans>
---输出信息如下所示:
message : 对象A
message : 对象A
----在bean.xml中将scope属性修改为prototype
<bean class="..." id="..." scope="prototype">
例2:修改配置文件 Beans.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-3.0.xsd">
<bean id="helloWorld" class="com.java265.HelloWorld" scope="prototype"/>
</beans>
运行结果如下。
message : 对象A
message : null