proxyMode ScopedProxyMode.TARGET_CLASS vs ScopedProxyMode.INTERFACE

前端 未结 2 1602
旧巷少年郎
旧巷少年郎 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:07

    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.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题