Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice to keep method visibility with Spring @Controller stereotype

My project at current job use private access modifier for methods of MVC controllers:

@Controller
public class HelloWorldController {

    @RequestMapping("/helloWorld")
    private ModelAndView helloWorld() {

I have integrated PMD and his report has a lot of:

/src/main/java/com/web/controller/SignalController.java:91: Avoid unused private
                                            methods such as 'handleNewRequest()'.

So instead of disabling useful PMD rule I think to change controller's methods visibility to public.

Are there any reasons to keep controller's methods private?

like image 792
gavenkoa Avatar asked Jul 10 '13 14:07

gavenkoa


People also ask

Can we replace @controller with @RestController?

So if you are using latest spring version you can directly replace @Controller with @RestController without any issue.

What happens when two methods with different view has same request mapping?

Unfortunately, this is not possible. The request mapping has to be unique otherwise the application can't determine which method the incoming request should be mapped to.

What happens when a class is annotated with the @controller annotation?

The @Controller annotation indicates that a particular class serves the role of a controller. There is no need to extend any controller base class or reference the Servlet API. You are of course still able to reference Servlet-specific features if you need to.

Is @controller thread safe?

What is Controller ? Controller is, thread-safe class, capable of handling multiple HTTP requests throughout the lifecycle of an application. CrudRepository provides sophisticated CRUD functionality for the entity class that is being managed.


1 Answers

You're shooting yourself in the foot by making it private:

  1. it's seen as unused by PMD and the IDEs (and, transitively, all the other private methods it calls, too). So you or a collegue might mistakenly remove private methods that are actually used.
  2. It makes it much harder to unit-test them.
  3. It's unconventional, making your code look weird to experienced Spring developers.
  4. They're logically public, since they're called by code outside of the class and package.
like image 92
JB Nizet Avatar answered Sep 28 '22 22:09

JB Nizet