spring生成对象默认是单例的。通过scope属性可以更改为多例。

<bean id="user" class="modle.User" scope="prototype">
</bean>

现在又这么一种情况.

User类调用一个service, 这个service又调用一个tool。

有时我们希望User是多例的,service是单例的,而tool又是多例的。

很自然地想法是配置文件这些写

<bean id="user" class="modle.User" scope="prototype">
<property name="service" ref="userservice"></property>
</bean> <bean id="userservice" class="service.userService" >
<property name="tool" ref="tool"></property>
</bean> <bean id="tool" class="service.ToolImpl" scope="prototype"></bean>

但是这种写法是错误的! 不能使用spring的自动注入!

由于service是单例的,所以这种方法的结果是:User多例,service和tool都是单例。(为什么?)

官网文档:

4.5.3 Singleton beans with prototype-bean dependencies

When you use singleton-scoped beans with dependencies on prototype beans, be aware that dependencies are resolved at instantiation time. Thus if you dependency-inject a prototype-scoped bean into a singleton-scoped bean, a new prototype bean is instantiated and then dependency-injected into the singleton bean. The prototype instance is the sole instance that is ever supplied to the singleton-scoped bean.

However, suppose you want the singleton-scoped bean to acquire a new instance of the prototype-scoped bean repeatedly at runtime. You cannot dependency-inject a prototype-scoped bean into your singleton bean, because that injection occurs only once, when the Spring container is instantiating the singleton bean and resolving and injecting its dependencies. If you need a new instance of a prototype bean at runtime more than once, see Section 4.4.6, “Method injection”

正确的写法是,是每次调用tool时都生成一个新的tool对象。但是我们又不能手动new一个,要借助BeanFactory

public class User {

	private userService service;
private int age;
private Date date;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public userService getService() {
return service;
}
public void setService(userService service) {
this.service = service;
} }

UserService 通过实现 BeanFactoryAware 接口来获得factory

由于不使用spring的自动注入,set方法要去掉!

public class userService implements BeanFactoryAware{

	private Tool tool;
private BeanFactory factory;
public void service(){
this.tool = (Tool)factory.getBean("tool");
System.out.println(this+":service");
tool.work();
}
public Tool getTool() { return tool;
}
// public void setTool(Tool tool) {
//
// this.tool = (Tool)factory.getBean("tool");
// }
public void setBeanFactory(BeanFactory f) throws BeansException {
factory = f;
} }

配置文件,不能再使用注入。因此要把tool对象的注入去掉!

<bean id="user" class="modle.User" scope="prototype">
<property name="service" ref="userservice"></property>
</bean> <bean id="userservice" class="service.userService" >
</bean> <bean id="tool" class="service.ToolImpl" scope="prototype"></bean>
public interface Tool {
public void work();
}
public class ToolImpl implements Tool{

	public void work() {
System.out.println(this+":Tool Work");
} }

测试类:

public class Test {
public static void main(String[] args) {
ClassPathResource res = new ClassPathResource("applicationContext.xml");
XmlBeanFactory factory = new XmlBeanFactory(res);
User user = (User)factory.getBean("user");
User user2 = (User)factory.getBean("user"); System.out.println(user);
user.getService().service();
System.out.println();
System.out.println(user2);
user2.getService().service();
}
}

Output:

modle.User@42552c
service.userService@19e15c:service
service.ToolImpl@11a75a2:Tool Work
modle.User@210b5b
service.userService@19e15c:service
service.ToolImpl@170888e:Tool Work

原文  http://blog.csdn.net/gaotong2055/article/details/8245036

 

(转载)spring单例和多例详解。如何在单例中调用多例对象的更多相关文章

  1. Native Application 开发详解(直接在程序中调用 ntdll.dll 中的 Native API,有内存小、速度快、安全、API丰富等8大优点)

    文章目录:                   1. 引子: 2. Native Application Demo 展示: 3. Native Application 简介: 4. Native Ap ...

  2. 使用Squid做代理服务器,Squid单网卡透明代理配置详解(转)

    使用Squid做代理服务器 说到代理服务器,我们最先想到的可能是一些专门的代理服务器网站,某些情况下,通过它们能加快访问互联网的速度.其实,在需要访问外部的局域网中,我们自己就能设置代理,把访问次数较 ...

  3. (转载)完成端口(Completion Port, I/OCP)详解

    http://www.cnblogs.com/lancidie/archive/2011/12/19/2293773.html 手把手叫你玩转网络编程系列之三    完成端口(Completion P ...

  4. 2017.2.13 开涛shiro教程-第十二章-与Spring集成(一)配置文件详解

    原博客地址:http://jinnianshilongnian.iteye.com/blog/2018398 根据下载的pdf学习. 第十二章-与Spring集成(一)配置文件详解 1.pom.xml ...

  5. 【Spring】——声明式事务配置详解

    项目中用到了spring的事务: @Transactional(rollbackFor = Exception.class, transactionManager = "zebraTrans ...

  6. Python的Django框架中forms表单类的使用方法详解

    用户表单是Web端的一项基本功能,大而全的Django框架中自然带有现成的基础form对象,本文就Python的Django框架中forms表单类的使用方法详解. Form表单的功能 自动生成HTML ...

  7. Spring Boot的每个模块包详解

    Spring Boot的每个模块包详解,具体如下: 1.spring-boot-starter 这是Spring Boot的核心启动器,包含了自动配置.日志和YAML. 2.spring-boot-s ...

  8. idea spring+springmvc+mybatis环境配置整合详解

    idea spring+springmvc+mybatis环境配置整合详解 1.配置整合前所需准备的环境: 1.1:jdk1.8 1.2:idea2017.1.5 1.3:Maven 3.5.2 2. ...

  9. spring boot 配置文件properties和YAML详解

    spring boot 配置文件properties和YAML详解 properties中配置信息并获取值. 1:在application.properties配置文件中添加: 根据提示创建直接创建. ...

  10. Spring全家桶——SpringBoot之AOP详解

    Spring全家桶--SpringBoot之AOP详解 面向方面编程(AOP)通过提供另一种思考程序结构的方式来补充面向对象编程(OOP). OOP中模块化的关键单元是类,而在AOP中,模块化单元是方 ...

随机推荐

  1. SQLServer 查询数据死锁语句

    SQLServer 查询数据死锁语句   我们可以通过以下SQL 语句用来查询,当前数据中存在的死锁语句,定位数据库出现死锁的根本原因.   --每秒死锁数量 SELECT * FROM sys.dm ...

  2. [others]tinycore/microcore

    https://zh.wikipedia.org/wiki/Tiny_Core_Linux https://github.com/zeit/micro

  3. [security][modsecurity][nginx] nginx 与 modsecurity

    参考文档: https://github.com/SpiderLabs/ModSecurity/wiki/Reference-Manual#installation-for-nginx nginx不支 ...

  4. (未完成)在block内如何修改block外部变量

    变量必须用__block修饰,否则编译不通过 block内部会把变量拷贝到堆区 变量从栈区copy->堆区 通过对对象取地址,打印出对象在内存中的地址 &a block不允许修改外部变量 ...

  5. LeetCode 965 Univalued Binary Tree 解题报告

    题目要求 A binary tree is univalued if every node in the tree has the same value. Return true if and onl ...

  6. TMS WEB Core v1.2预览版:新的Electron应用程序支持

    2019年2月20日,星期三 几个月前,我们已经开始与Electron进行实验.在工作概念验证之后,我们的目标是为Delphi开发人员尽可能多地包装Electron API.但当然不仅仅是可以使用的E ...

  7. html5页面自适应移动端

    1. <!-- 这段代码的意思是,让 viewport 的宽度等于物理设备上的真实分辨率,不允许用户缩放,这样 dpi 肯定和设备上的真实分辨率是一样的,不做任何缩放,网页会因此显得更细腻. 1 ...

  8. 【PyQt5-Qt Designer】简易的数字键盘输入+简易计算器

    参考如下键盘格式写了一个键盘输入,目前还不能进行运算,后期完善... 效果如下: 完整代码: from PyQt5.QtWidgets import (QApplication,QWidget,QPu ...

  9. es6 学习四 数组的学习

    1. Array.from() 语法: Array.from(arrayLike[, mapFn[, thisArg]]) arrayLike 类数组对象 mapFn 如果指定了该参数,新数组中的每个 ...

  10. IO和NIO

    一.创建IO System.out.println( "*************欢迎进入文件操作系统*************" ); System.out.println( & ...