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