As other SO answers suggested, use proxy mode type as per your need, I am still confused;
@Configuration
@ComponentScan
public class Application
{
publi
I created an interface PrototypeBeanI with sayHello and used the interface in the main(), still different results. seems that using PrototypeBeanI or PrototypeBean as the variable type does not create any difference.
@Component
@Scope(value="prototype", proxyMode = ScopedProxyMode.INTERFACES)
public class PrototypeBean { ... }
This, in your case, will lead to a bean per invocation of getBean
bean as your PrototypeBean
doesn't implement an interface and as such a scoped proxy cannot be created. In your case you call the lookup method twice and hence you will get 2 instances. This is actually the normal behavior of a prototype
scoped bean.
Component
@Scope(value="prototype", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class PrototypeBean { ... }
This will lead to the creation of a proxy. That proxy is created once and will be returned for each call to getBean
. As soon as you invoke a method on the proxy it will, based on the scope, either create a new one or reuse an existing one. As you have specified the scope as prototype
each method invocation will lead to a new object.
Note: If your class would implement an interface which exposes the appropriate method, there would be no difference in the behavior of proxyMode = ScopedProxyMode.INTERFACES
and proxyMode = ScopedProxyMode.TARGET_CLASS
as in both cases a scoped proxy would be created.