How will a prototype bind behave within a singleton?
sobes.tech AI
Answer from AI
A bean with prototype scope injected into a singleton bean will be created once during the singleton's initialization and then used multiple times (the same instance) each time it is accessed from the singleton. Spring creates a prototype bean each time it is requested from the container. When injected into a singleton, the request occurs only during the singleton's creation.
To solve this problem and obtain a new instance of the prototype bean each time it is accessed, you can use the following approaches:
-
Injecting
ApplicationContext: Explicitly retrieve the bean from the context each time.// Getting a prototype bean from the context PrototypeBean prototypeBean = applicationContext.getBean(PrototypeBean.class); -
Injecting
ObjectFactory<PrototypeBean>orProvider<PrototypeBean>: Spring will provide a proxy that, when callinggetObject()(forObjectFactory) orget()(forProvider), will request a new instance from the context.// Using ObjectFactory to get a new instance @Autowired private ObjectFactory<PrototypeBean> prototypeBeanFactory; // ... public void someMethod() { PrototypeBean prototypeBean = prototypeBeanFactory.getObject(); // ... use the new prototypeBean instance } -
Using
@Lookupannotation: Create an abstract getter in the singleton, marked with@Lookup. Spring will generate a subclass of the singleton that overrides this method to obtain a new prototype bean.// Using @Lookup @Lookup public abstract PrototypeBean getPrototypeBean(); // ... public void someMethod() { PrototypeBean prototypeBean = getPrototypeBean(); // ... use the new prototypeBean instance }