Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Spring Controllers Implementing Interfaces?

DZone 's Guide to

Spring Controllers Implementing Interfaces?

Want to learn more about Spring Controllers?

· Java Zone ·
Free Resource

Getting the following error when Spring Controller implements interfaces:

The mapped controller method class  com.xyz.AbcController is 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).

Why?

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 InvocableHandlerMethod.assertTargetBean method.

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).

Finally

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.

Topics:
spring ,spring controllers ,controllers ,java ,interfaces ,error

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}