1、由 spring 产生的 bean 默认的是单例的。
2、可以在 spring 的配置文件中,用 scope 属性控制“singleton/prototype(多例)/request/session/global session”<bean id="scope" class="cn.google.spring.scope.Scope" scope="singleton"></bean>
3、如果 spring 的配置文件的scope为 “prototype”,则在得到该 bean 时才创建对象。
示例代码:
1、建 Helloworld.java
public class HelloWorld {
public HelloWorld(){
System.out.println("new instance ------");
}
public void hello(){
System.out.println("hello");
}
}
2、applicationContext-scope.xml 中
<bean id="helloScope" class="cn.google.spring.scope.HelloWorld" scope="singleton"></bean>
3、测试代码:
@Test
public void testScope(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
HelloWorld helloWorld =(HelloWorld) context.getBean("helloScope");
HelloWorld helloWorld2 =(HelloWorld) context.getBean("helloScope");
s.o.p(helloWorld);
s.o.p(helloWorld2);
}