There will be problems in injecting Spring's prototype into singleton. For details, see
The useless solution of Spring Bean's prototype
In addition to the methods introduced in this article (ApplicationContext.getBean and proxy mode), there are other implementations in the java (Spring) world.
Let's talk about it here.
1. Using Spring's ObjectFactory
If the original code is like this
@Autowired private PrototypeBean bean;
If it is used directly in a single instance or obtained multiple times in multiple instances, the same instance will be obtained.
Our state bean is invalid.
can be changed to this
@Autowired private ObjectFactory<PrototypeBean> bean;
Call the getObject method when using
bean.getObject()
That's it.
2. Using Provider<T> proposed by Java's JSR 330
To introduce the jar package javax.inject
import javax.inject.Provider;
The usage is similar to the previous ObjectFactory, except that the method name becomes get
In my opinion, the difference between Provider and ObjectFactory is the difference between Resource and Autowire.
3. Use Spring's Lookup annotation
import org.springframework.beans.factory.annotation.Lookup; import org.springframework.stereotype.Component; @Component public class MySingletonBean { public void showMessage(){ MyPrototypeBean bean = getPrototypeBean(); //do your own logic } @Lookup public MyPrototypeBean getPrototypeBean(){ //spring will override this method by itself return null; } }
This way you don't need to inject a property, but add a method that returns null.