SpringIOC_对象的多实例和单实例
2015-11-01 19:21
302 查看
[b]一个对象在Spring容器中到底是多例还是单例呢?[/b]
[b]默认为单例,在scope设置为prototype的时为多例,当为多例时,对象的创建时发生改变,无论lazy-init为什么值,[/b][b]都是在context.getBean();时创建对象[/b]
1.ApplicationContext.xml
2.测试代码
Helloword
3.测试
[b]默认为单例,在scope设置为prototype的时为多例,当为多例时,对象的创建时发生改变,无论lazy-init为什么值,[/b][b]都是在context.getBean();时创建对象[/b]
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 //com.spring.scope.HelloWord@29a3a9db //com.spring.scope.HelloWord@29a3a9db } /** * * 如果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 com.spring.scope.HelloWord@79d0e2d2 com.spring.scope.HelloWord@db8779 */ } }
相关文章推荐
- Java四种读取和创建XML文档的例子教程
- Java os.name
- jfinal spring 整合 集成 事物 spring-jfinal
- java中的垃圾收集算法
- jfinal集成spring cxf做webservice服务
- spring 注解事务配置
- spring 注解事务配置
- PAT 1019. General Palindromic Number (20)
- eclipse 常用快捷键
- SpringIOC_创建对象的时机
- java学习笔记.07——内部类
- PAT 1018. Public Bike Management (30)
- java编程之美(一)
- java编程之美(一)
- JAVA i++线程非安全测试1
- JAVA i++线程非安全测试1
- 使用fat jar和proguard对包含第三方依赖包的java代码进行打包混淆
- spring中AOP3
- Eclipse创建Django项目
- java怎样杀死一个指定线程