Is there any reason to proxy a singleton bean?

798 Views Asked by At

I've seen the following definition in the code:

@Scope(proxyMode = ScopedProxyMode.TARGET_CLASS)
@Component
public class SomeComponent {
  <...>
}

This is a singleton scoped bean. And it seems for me, that there is no reason to proxy it. As far as I understand we should to proxy a bean in case if its scope isn't singleton and differs from a scope of another bean, into which we are going to inject it.

Probably I don't know something. What may be a reason to proxy a singleton?

2

There are 2 best solutions below

0
On BEST ANSWER

After an investigation I found an answer for my question in an outdated Spring's documentation:

You do not need to use the <aop:scoped-proxy/> in conjunction with beans that are scoped as singletons or prototypes. It is an error to try to create a scoped proxy for a singleton bean (and the resulting BeanCreationException will certainly set you straight in this regard).

It answers my question, because <aop:scoped-proxy/> is an alternative for @Scope annotation. But current documentation differs from the old one:

You may also use <aop:scoped-proxy/> between beans that are scoped as singleton, with the reference then going through an intermediate proxy that is serializable and therefore able to re-obtain the target singleton bean on deserialization.

It means, now you will not see BeanCreationException in case if you will try to define a singleton scoped proxy. But anyway, I don't fully understand the purpose of this vague use-case. So, if anyone understands what this statement means, please, clarify it in comments.

Conclusion: In the most cases there is no reason to proxy a singleton scoped bean.

0
On

Regarding the scoped proxy: this is what written in Spring documentation.

Note:

You do not need to use the in conjunction with beans that are scoped as singletons or prototypes. It is an error to try to create a scoped proxy for a singleton bean (and the resulting BeanCreationException will certainly set you straight in this regard).

Although it refers a pretty old version, but the note is still valid IMO. I've never tried this by myself though.

Having said that, there can be a lot of reasons to proxy the singleton bean, "proxy" is a very broad concept. For example, when we use @Transactional its a proxy, there are many other examples. The thing is that this is not a "scoped proxy" which can be treated as a very specific kind of proxy which is apparently not applicable to singletons.