Spring Controllers Implementing Interfaces?
Want to learn more about Spring Controllers?
Join the DZone community and get the full member experience.Join For Free
Getting the following error when Spring Controller implements interfaces:
The mapped controller method class
com.xyz.AbcControlleris not an instance of the actual controller bean instance
com.sun.proxy.$Proxy108. If the controller requires proxying (e.g. due to
@Transactional), please use class-based proxying.
The error is crystal clear, and provides a suggestion on how to fix the problem:
The solution would be to make sure class-based proxying is used (as shown in line number 2).
As per spring proxying:
Spring AOP uses either JDK dynamic proxies or CGLIB to create the proxy for a given target object. (JDK dynamic proxies are preferred whenever you have a choice).
If the target object to be proxied implements at least one interface then a JDK dynamic proxy (if ther is a
$ProxyXXX, it means there is an interface) will be used. All of the interfaces implemented by the target type will be proxied. If the target object does not implement any interfaces then a CGLIB proxy will be created.
Now, since the
com.xyz.AbcController is marked with
@Controller (which is a specialization of
@Component), and when it implements an interface, a proxy of that interface is created. Since the
@RequestMappingmethod is not present in the interface, an error is thrown. This can be seen in the
The issue is overcome by switching to class-based proxying (using CGLIB, which works by dynamically creating a subclass of the original bean as proxy).
The best practice is implementing the
@Controllerannotation on concrete classes, and it is advisable not implement any interface, If we do, then proper measures have to be taken to make sure (a) it is a concerned interface and (b) proper annotations are present in the interface.
Published at DZone with permission of Mohammad Nadeem, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Adding Mermaid Diagrams to Markdown Documents
A Complete Guide to Agile Software Development
How AI Will Change Agile Project Management
An Overview of Cloud Cryptography