一个对象在Spring容器中到底是多例还是单例呢?
默认为单例,在scope设置为prototype的时为多例,当为多例时,对象的创建时发生改变,无论lazy-init为什么值,都是在context.getBean();时创建对象
1.ApplicationContext.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="helloWorld" class="com.spring.scope.HelloWord"></bean> <bean id="helloWorld2" class="com.spring.scope.HelloWord" scope="prototype"></bean> </beans>
2.测试代码
Helloword
package com.spring.scope; public class HelloWord { public HelloWord(){ System.out.println("create Object"); } public void hello(){ System.out.println("hello word!"); } }
3.测试
package com.spring.scope.test; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.spring.scope.HelloWord; public class HelloWordTest { /** * *在Spring容器中的对象,默认情况下是单例的 * 因为对象是单列的,所以只要在类上声明一个属性,该属性含有数据,那么这个该属性将是全局的 (危险) */ @Test public void testScope_Default(){ //启动Spring容器 ApplicationContext context= new ClassPathXmlApplicationContext("applicationContext.xml"); //根据id把Spring容器中的bean提取出来 HelloWord helloWord = (HelloWord) context.getBean("helloWorld"); HelloWord helloWord2 = (HelloWord) context.getBean("helloWorld"); System.out.println(helloWord); System.out.println(helloWord2); //create Object //[email protected] //[email protected] } /** * * 如果scope为prototype,Spring容器产生的对象就是多例 * * 如果一个对象为多例,这个对象在Spring容器中创建时机就会发生改变,则不会再启动的时候创建对象,会再getBean()才创建对象 * 即: * 如果scope为prototype,则无论Lazy-init为什么值,都是在 context.getBean()时创建对象。 * */ @Test public void testScope_Prototype(){ //启动Spring容器 ApplicationContext context= new ClassPathXmlApplicationContext("applicationContext.xml"); //根据id把Spring容器中的bean提取出来 HelloWord helloWord = (HelloWord) context.getBean("helloWorld2"); HelloWord helloWord2 = (HelloWord) context.getBean("helloWorld2"); System.out.println(helloWord); System.out.println(helloWord2); /* create Object create Object [email protected] [email protected] */ } }
时间: 2024-10-06 18:33:04