Junior — Middle
Is it possible to use prototype beans within other beans in Spring?
sobes.tech AI
Answer from AI
In Spring, you can use prototype beans inside singleton beans, but it is important to note that by default, a prototype bean is created only once when the singleton bean is created, and the same instance is used thereafter.
To get a new instance of a prototype bean inside a singleton each time, you can use:
- ObjectFactory or Provider — inject a factory that will create a new bean upon request.
- @Lookup method — annotate a method that will return a new instance of the prototype bean.
Example with @Lookup:
@Component
@Scope("singleton")
public class SingletonBean {
@Lookup
public PrototypeBean getPrototypeBean() {
// Spring will override this method to return a new PrototypeBean
return null;
}
public void usePrototype() {
PrototypeBean prototype = getPrototypeBean();
prototype.doSomething();
}
}
@Component
@Scope("prototype")
public class PrototypeBean {
public void doSomething() {
System.out.println("Executing prototype bean");
}
}
Thus, you can use prototype beans inside other beans, but to correctly obtain new instances, you need to use special mechanisms.