Spring / Spring Beans
What happens when a singleton bean contains a prototype bean?
The prototype bean is created only once, when the singleton is created. This means you won't get a new prototype instance every time the singleton uses it.
@Component @Scope("singleton") public class SingletonBean { @Autowired private PrototypeBean prototypeBean; public void show() { System.out.println(prototypeBean.hashCode()); } }
All calls to show() print the same hashCode (same PrototypeBean instance).
Fix: Use @Lookup method or ObjectFactory/Provider injection.
@Autowired private ObjectFactory<PrototypeBean> prototypeFactory; public void show() { System.out.println(prototypeFactory.getObject().hashCode()); }
More Related questions...