Spring Singleton Bean and prototype bean dependency

Source: Internet
Author: User

This document is synchronized to: http://www.waylau.com/spring-singleton-beans-with-prototype-bean-dependencies/

Problem

We know that the Spring bean default scope is singleton (singleton), but some scenarios (such as multithreading) require each call to generate an instance,
At this point, scope should be set to prototype. Such as:

     * @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);    }}

However, if the Singlton Bean relies on the prototype bean, the prototype bean is created once (only once) when instantiated by the Singlton bean through a dependency injection method.
Like what:

@Servicepublic 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);    }}

I want to dispatch "Lily" and "Lucy" two threads, in fact, it only initializes an instance of me (so the thread is not secure).

Solve

If the Singlton Bean wants to create a new instance of the prototype bean every time, it needs to be injected by means of a method.
You can get to the ApplicationContext instance by implementing the Applicationcontextaware interface,
The Getbean method is then used to obtain an instance of the prototype bean. Our program needs to be modified as follows:

@Servicepublic 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, Problem solving

Source

See Catalogue in Https://github.com/waylau/spring-framework-4-demos beanScope

Reference
    • Spring Framework 4.x reference documentation

Spring Singleton Bean and prototype bean dependency

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.