bean的作用域比較容易理解撑蚌,我們通過(guò)一個(gè)小示例說(shuō)明(工程spring_scope
)。
bean的作用域主要由scope屬性來(lái)決定:
- singleton(默認(rèn))刽肠,每次調(diào)用getBean的時(shí)候返回相同的實(shí)例溃肪;
- prototype,每次調(diào)用getBean的時(shí)候返回不同的實(shí)例音五。
給出一個(gè)實(shí)體類:
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>
測(cè)試: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");
}
}
}
說(shuō)明:如果我們使用默認(rèn)的scope域惫撰,那么bean11和bean12是相同的,如果使用prototype則是不想等的躺涝。