bean的作用域比较容易理解,我们通过一个小示例说明(工程spring_scope
)。
bean的作用域主要由scope属性来决定:
- singleton(默认),每次调用getBean的时候返回相同的实例;
- prototype,每次调用getBean的时候返回不同的实例。
给出一个实体类:
Bean1.java
package com.bjsxt.spring;
public class Bean1 {
}
配置:applicationContext-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" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
<!--
<bean id="bean1" class="com.bjsxt.spring.Bean1" scope="singleton"/>
-->
<bean id="bean1" class="com.bjsxt.spring.Bean1" scope="prototype"/>
</beans>
测试:ScopeTest.java
package com.bjsxt.spring;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import junit.framework.TestCase;
public class ScopeTest extends TestCase {
private BeanFactory factory;
@Override
protected void setUp() throws Exception {
factory = new ClassPathXmlApplicationContext("applicationContext-*.xml");
}
public void testScope1() {
Bean1 bean11 = (Bean1)factory.getBean("bean1");
Bean1 bean12 = (Bean1)factory.getBean("bean1");
if (bean11 == bean12) {
System.out.println("bean11==bean12");
}else {
System.out.println("bean11!=bean12");
}
}
}
说明:如果我们使用默认的scope域,那么bean11和bean12是相同的,如果使用prototype则是不想等的。