Search code examples
javaspring-mvc

spring-mvc controller public or package-private


What's different in public vs package-private method in the following code?

    @RequestMapping("/")
    String home(){
       "Hello World!"
    }

    @RequestMapping("/")
    public String home(){
       "Hello World!"
    }

Is it just mean public and protected in java?


Solution

  • In this case, since no one other than Spring and your unit tests should call these methods, making them public or protected doesn't change much.

    I would leave them public because

    • protected makes it look like the method is intended to be overridden, which it's not
    • public makes it look like the method is intended to be called from the outside world, which it is (except it's being called through HTTP, and Spring is the one actually calling the method)
    • if you need to make that method transactional, or otherwise proxied, then the method should be public