spring支持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环境 |
- singleton
(1)bean中设定为singleton的作用域
<?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="hellospring" class="com.springstudy.HelloSpring" scope="singleton">
<!-- <property name="message" value="Hello Spring!!!"/> -->
</bean>
</beans>
java 代码
package com.springstudy;
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");
HelloSpring obj1 = (HelloSpring) context.getBean("hellospring");
obj1.setMessage("i am object1");
obj1.getMessage();
HelloSpring obj2 = (HelloSpring) context.getBean("hellospring");
obj2.getMessage();
}
}
package com.springstudy;
public class HelloSpring {
private String message;
public void getMessage() {
System.out.println("Your Message is : " + message);
}
public void setMessage(String message) {
this.message = message;
}
}
运行结果:
- prototype
将bean中的作用域改为prototype
<?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="hellospring" class="com.springstudy.HelloSpring" scope="prototype ">
<!-- <property name="message" value="Hello Spring!!!"/> -->
</bean>
</beans>
运行结果: