0
votes

I was in the impression that whenever a class implements an interface then JDK based proxies are created.

I have a bean which implements an interface with prototype scope which is injected in a bean with singleton scope. I tried using proxyMode = ScopedProxyMode.INTERFACES JDK proxy was created which is right, but when I tired proxyMode = ScopedProxyMode.TARGET_CLASS then CGLIB based proxy is created even though my bean implements an interface.

what happens when

proxyMode = ScopedProxyMode.TARGET_CLASS

and

proxyMode = ScopedProxyMode.INTERFACES

what is the difference between them? when to use which one?

One more question I have is what is the correct way to inject prototype bean into singleton bean?

1
That is what you told the framework to do is to always create class based proxies and thus cglib based proxies. - M. Deinum

1 Answers

2
votes

In general, no proxy is needed in a scenario where a prototype scoped bean is injected into a singleton scoped bean.

The reference documentation states:

You do not need to use the <aop:scoped-proxy/> in conjunction with beans that are scoped as singletons or prototypes.

What happens without a proxy?

When the Spring context is being created and the singleton bean instantiated, a new instance of the prototype bean is created and injected into the singleton. Every invocation of our singleton now uses the same instance of the prototype.

Why would you need the proxy?

Maybe you want to alter the default behavior and create a new prototype bean instance for every invocation of the singleton bean. With the proxy, the singleton bean will keep the same proxy instance for all invocations. With every invocation, the proxy will get a new prototype bean instance from the Spring context.

The proxy modes

The proxy modes are self-descriptive. See ScopeProxyMode Javadoc:

  • ScopeProxyMode.INTERFACES - Create a JDK dynamic proxy implementing all interfaces exposed by the class of the target object.
  • ScopeProxyMode.TARGET_CLASS - Create a class-based proxy (uses CGLIB).

Does the singleton bean depend on an interface implemented by the prototype bean? Use ScopeProxyMode.INTERFACES. Otherwise, use ScopeProxyMode.TARGET_CLASS.

A method injection would be an alternate approach to get the same behavior as with the proxy.