I am looking for a way to store my object and it seems that the best approach is to use proxies. I found 2 annotation in the internet, which one should I use :
@Scope(value = "session", proxyMode = ScopedProxyMode.INTERFACES)
or
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS )
Moreover, is it true that the proxies is the best way to use than using @Component
@Scope("session")
or using @SessionAttributes
?
If you want to store the whole bean in the session, use @Scope, otherwise use @SessionAttributes. In the case of using @Scope, if the class implements some interfaces then use INTERFACES proxy mode, if not use TARGET_CLASS.
Usually your service implements an interface, which allows the use of JDK proxies (INTERFACES mode). But if that is not the case then use TARGET_CLASS, which creates a CGLIB proxy.
Using INTERFACES should be used if possible and TARGET as last resort if the bean does not implement interfaces.
You'll need to understand what each of those annotations does to choose for yourself. See the javadoc, here. Continue for a more detailed explanation.
The first
creates
In other words, the proxy will be a subtype of the interfaces that the target object's class implements, but won't be a subclass of the target object's class itself.
Essentially Spring does the following
The proxy returned won't be of type
Foo
and you therefore can't inject it into any targets of that type. For example, Spring will fail to inject it into a field likebut will successfully inject the proxy into a field like
All calls to the proxy will be handled by the
InvocationHandler
(which usually performs some use case specific logic then delegates to the target object).The second annotation
creates
In addition to interfaces, with CGLIB Spring will be able to create a proxy whose class is a subclass of the target's class. In essence, it does the following
CGLIB creates a new class that is a subclass of
Foo
and instantiates it (invoking the constructor ofFoo
). All calls to the proxy will be intercepted by the provided callback (which usually performs some use case specific logic and then delegates to the target object).Since the proxy class extends
Foo
, Spring can inject the proxy into a field (or constructor/method parameter) likeAll this to say, if you're programming to interfaces, then
ScopedProxyMode.INTERFACES
will be sufficient. If you're not, then useScopedProxyMode.TARGET_CLASS
.As for using
@SessionAttributes
, it is not an alternative to session scoped beans. Session attributes are just objects, they are not beans. They don't possess the full lifecycle, injection capabilities, proxying behavior that a bean may have.While going through a blog post provided in the comments above, I found a comment stating cons of interface-based proxies.
On the post, user Flemming Jønsson posted this: