1.spring bean作用域demo
spring创建的bean默认是单例的。也就是无论你通过getBean还是装配,获得的bean都是同一个。
修改前面的sing类加一个计数变量。
package com.amber.ivy.spring.bean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* 测试类
* @author ivyamber
*
*/
public class BeanTest {
private static Engineer e;
private static Performer p;
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("com/amber/resource/bean.xml");
p = (Performer) context.getBean("performer");
p.perform();
Performer p2 = (Performer) context.getBean("performer");
p2.perform();
}
}
打印:i am singing0
i am singing1
修改默认,不使用单例
<?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="engineer" class="com.amber.ivy.spring.bean.SoftwareEngineer">
<constructor-arg value="java"/>
<constructor-arg ref="performer"/>
</bean>
<bean id="performer" class="com.amber.ivy.spring.bean.Sing" scope="prototype"/>
</beans>
打印:i am singing0
i am singing0
2.bean的scope属性可以设定bean的作用域
作用域 | 定义 |
singleton | 在一个spring容器中,一个bean定义只有一个实例(默认) |
prototype | 允许bean的定义可以被实例化任意次(每次调用都创建一个实例) |
request | 在一次http请求中,每个bean定义对应一个实例。该作用域仅在基于web的spring上下文(例如spring mvc)中才有效 |
session | 在一次http session中,每个bean定义对应一个实例。该作用域仅在基于web的spring上下文(例如spring mvc)中才有效 |
global-session | 在一个全局http session中,每个bean定义对应一个实例。该作用域仅在基于web的spring上下文中才有效 |