<!-- <bean id="bean1" class="spring.Bean1" scope="singleton"/> --> <bean id="bean1" class="spring.Bean1" scope="prototype"/>
spring Bean的作用域:主要由<bean>标签的属性scope决定。
scope可以取值:
* singleton:每次调用getBean的时候返回相同的实例
* prototype:每次调用getBean的时候返回不同的实例
例子代码:
Bean.java:
public class Bean {
}
applicationContext.xml:
测试代码:
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");
}
}
}