Don't Complicate Spring Controllers With Commotions
source link: https://www.tuicool.com/articles/hit/MfyUBv2
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
@Controller Implementing Interface
You may get into the problem as described below
The mapped controller method class 'com.xyz.ABController'
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.
So, it is better not to do the following:
Don’t
@Controller public class SomeController implements SomeConcerenedInterface { }
@Controller Extending Another @Controller
If the intent is to share the logic, it is better to do it with composition. In this case, the reason is you may end up exposing an endpoint unintentionally in ChildController
,
which may be inherited from the ParentController
.
Further, that is the old way of doing things, before Annotations in Spring.
Don’t
@Controller public class ParentController { } @Controller public class ChildController extends ParentController { }
Simple Controller
The best practice is to keep the @Controller
class simple, as shown below (don’t implement the interface and don't extend another controller), @Controller
should expose an endpoint, and the processing logic should be delegated to another abstraction. This way, logic can be shared across multiple @Controllers
if required.
Do
@Controller public class SomeController { }
@Controller Extending Another BasClass
This case should be avoided as much as possible. If possible, use composition here:
May Do
public class SomeBaseClassWithOutControllerAnnotation { //May contain methods Without @RequestMapping } **//Discouraged** @Controller public class SomeController extends SomeBaseClassWithOutControllerAnnotation { }
Happy controlling!
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK