proxyMode ScopedProxyMode.TARGET_CLASS vs ScopedProxyMode.INTERFACE

前端 未结 2 1613
旧巷少年郎
旧巷少年郎 2021-01-01 04:01

As other SO answers suggested, use proxy mode type as per your need, I am still confused;

@Configuration
@ComponentScan
public class Application 
{
    publi         


        
2条回答
  •  攒了一身酷
    2021-01-01 04:30

    @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.

提交回复
热议问题