Spring singleton bean 与 prototype bean 的依赖

本文同步至:http://www.waylau.com/spring-singleton-beans-with-prototype-bean-dependencies/

问题

我们知道,Spring bean 默认的 scope 是 singleton(单例),但有些场景(比如多线程)需要每次调用都生成一个实例,
此时 scope 就应该设为 prototype。如:

     * @see java.lang.Runnable#run()
@Scope("prototype")
public class DadTask implements Runnable {
    static Logger logger = Logger.getLogger(DadTask.class);

    @Autowired
    DadDao dadDao;

    private String name;
    /**
     *
     */
    public DadTask setDadTask(String name) {
        this.name = name;
        return this;
    }

    /* (non-Javadoc)
     * @see java.lang.Runnable#run()
     */
    @Override
    public void run() {
        logger.info("DadTask:"+this + ";DadDao:"+dadDao + ";"+dadDao.sayHello(name) );
        //logger.info("Dad:"+name);
    }

}

但是,如果 singlton bean 依赖 prototype bean ,通过依赖注入方式, prototype bean 在 singlton bean 实例化时会创建一次(只一次),
比如:

@Service
public class UserService {

    @Autowired
    private DadTask dadTask;

    public void startTask() {
        ScheduledThreadPoolExecutor  scheduledThreadPoolExecutor  = new ScheduledThreadPoolExecutor(2);

        scheduledThreadPoolExecutor.scheduleAtFixedRate(dadTask.setDadTask("Lily"), 1000, 2000, TimeUnit.MILLISECONDS);
        scheduledThreadPoolExecutor.scheduleAtFixedRate(dadTask.setDadTask("Lucy"), 1000, 2000, TimeUnit.MILLISECONDS);
    }
}

我希望调度“Lily” 和 “Lucy” 两个线程,实际上,它只给我初始化一个实例(这样就线程非安全了)。

解决

如果 singlton bean 想每次都去创建一个新的 prototype bean 的实例, 需要通过方法注入的方式。
可以通过实现 ApplicationContextAware 接口,来获取到 ApplicationContext 实例,
继而通过 getBean 方法来获取到 prototype bean 的实例。我们的程序需要修改如下:

@Service
public class UserService implements ApplicationContextAware {

    @Autowired
    private DadTask dadTask;

    private ApplicationContext applicationContext;

    public void startTask() {
        ScheduledThreadPoolExecutor  scheduledThreadPoolExecutor  = new ScheduledThreadPoolExecutor(2);

        // 每次都拿到 DadTask 的实例
        dadTask = applicationContext.getBean("dadTask", DadTask.class);
        scheduledThreadPoolExecutor.scheduleAtFixedRate(dadTask.setDadTask("Lily"), 1000, 2000, TimeUnit.MILLISECONDS);
        dadTask = applicationContext.getBean("dadTask", DadTask.class);
        scheduledThreadPoolExecutor.scheduleAtFixedRate(dadTask.setDadTask("Lucy"), 1000, 2000, TimeUnit.MILLISECONDS);
    }

    @Override
    public void setApplicationContext (ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;

    }
}

OK ,问题解决

源码

https://github.com/waylau/spring-framework-4-demosbeanScope 目录

参考

时间: 2024-08-02 12:05:10

Spring singleton bean 与 prototype bean 的依赖的相关文章

Spring 4.2 方法注入解决单例Bean的原型Bean依赖问题

当你在单例Bean中使用原型Bean依赖时,注意,依赖在实例化时解析.因此,如果你依赖注入一个原型Bean到单例Bean中,新的原型Bean被实例化然后依赖注入到单例Bean中.提供给单例Bean的原型实例是唯一的. 然而,假设你想单例Bean在运行时多次获取一个新的原型Bean的实例.你不能依赖注入一个原型Bean到你的单例Bean中,因为注入只发生一次,当Spring容器实例化单例Bean时解析并注入它的依赖.如果你在运行时多次需要一个新的原型Bean,可以使用方法注入. 在大多数应用程序情

Spring实战3:装配bean的进阶知识

主要内容: Environments and profiles Conditional bean declaration 处理自动装配的歧义 bean的作用域 The Spring Expression Language 在装配bean—依赖注入的本质一文中,我们探讨了Spring的三种管理bean的方式:自动装配.基于JavaConfig.基于XML文件.这篇文字将探讨一些Spring中关于bean的管理的高级知识,这些技能你可能不会每天都用,但是非常重要. 3.1 Environments

Spring之IOC&DI/装配Bean(一)

简介 今天学习Spring的第一天,无非也就是入门基础知识.主要了解IOC和DI部分,要熟练掌握哦~ Spring简介 1. Spring介绍 Spring是一个非常活跃的开源框架:它是一个基于Core来构架多层JavaEE系统的框架,它的主要目地是简化企业开发. Spring以一种非侵入式的方式来管理你的代码,Spring提倡"最少侵入",这也就意味着你可以适当的时候安装或卸载Spring 2. Spring框架的优势 ?方便解耦,简化开发 ?Spring就是一个大工厂,可以将所有对

看看Spring的源码(二)——bean实例化

首先来看一段代码,看过上一节的朋友肯定对这段代码并不陌生.这一段代码诠释了Spring加载bean的完整过程,包括读取配置文件,扫描包,加载类,实例化bean,注入bean属性依赖. public void refresh() throws BeansException, IllegalStateException { synchronized (this.startupShutdownMonitor) { // Prepare this context for refreshing. prep

Spring框架—— IOC容器和Bean的配置

 1 IOC和DI ①IOC(Inversion of Control):反转控制. 在应用程序中的组件需要获取资源时,传统的方式是组件主动的从容器中获取所需要的资源,在这样的模式下开发人员往往需要知道在具体容器中特定资源的获取方式,增加了学习成本,同时降低了开发效率. 反转控制的思想完全颠覆了应用程序组件获取资源的传统方式:反转了资源的获取方向--改由容器主动的将资源推送给需要的组件,开发人员不需要知道容器是如何创建资源对象的,只需要提供接收资源的方式即可,极大的降低了学习成本,提高了开发的效

Spring笔记——6.容器中bean的生命周期

spring可以管理单例bean的生命周期,知道何时被创建,核实初始化,何时销毁,也可以进行某些通用资源申请,销毁前资源回收.对于prototype,容器只负责创建,之后就撒手不管自生自灭.容器不知道一共创建了多少prototype,也不知道他们什么时候会被销毁,所以容器没法管理prototype. 管理bean的生命周期有如下两个时机: 注入依赖关系后 即将销毁bean前 依赖关系注入后的行为 通过设定init-method属性指定某个方法或者实现InitializingBean接口指定需要实

从启动日志看Spring IOC的初始化和Bean生命周期

一.Tomcat中启动IoC容器的日志 启动Tomcat等容器时,控制台每次都打印出一些日志. 最近刚好在研究Spring源码,所以换个角度,从启动日志来简单的看看Spring的初始化过程! 以下是Tomcat启动时日志,截取Spring部分. //------------------------------------- //从这里开始Spring的初始化 十一月 10, 2015 8:52:03 上午 org.apache.catalina.core.ApplicationContext l

Spring -- Bean自动装配&Bean之间关系&Bean的作用域

Bean的自动装配 Spring IOC 容器可以自动装配 Bean. 需要做的仅仅是在 的 autowire 属性里指定自动装配的模式 有以下几种自动装配的类型: byType(根据类型自动装配): 若 IOC 容器中有多个与目标 Bean 类型一致的 Bean. 在这种情况下, Spring 将无法判定哪个 Bean 最合适该属性, 所以不能执行自动装配. byName(根据名称自动装配): 必须将目标 Bean 的名称和属性名设置的完全相同. constructor(通过构造器自动装配):

SSH 之 Spring的源码(二)——Bean实例化

首先来看一段代码,看过上一节的朋友肯定对这段代码并不陌生.这一段代码诠释了Spring加载bean的完整过程,包括读取配置文件,扫描包,加载类,实例化bean,注入bean属性依赖. <span style="font-size:18px;">public void refresh() throws BeansException, IllegalStateException { synchronized (this.startupShutdownMonitor) { //