Search code examples
javaspringspring-bootspring-annotations

How to split classes to use serveral @Controller


I am learning spring boot, and i developed the below simple example. I would like to annotate a class as Controller using @Controller. this class has constructor and I want to have access to GreetingFromDeuController as shown:

http://localhost:8080:/GreetingFromDeuController?str = "hi"

the error i am receiving is

@RequestMapping is not applicable on a constructor

please let me know how to solve.

code:

@Controller
@RequestMapping("/GreetingFromDeuController")
public class GreetingFromDeuController {

private String str;

@RequestMapping("/GreetingFrom/deu")
GreetingFromDeuController(@RequestParam(value = "str") String str) {
    this.str = str;
}

@RequestMapping("/GreetingFromDeuController")
public String getGreetingFromDeu() {
    return this.str;
}   
}

Solution

  • The @RequestMapping documentation says:

    Annotation for mapping web requests onto methods in request-handling classes with flexible method signatures.

    Then you can not do that, if you want to initialize your variables or whatever you can use several ways:

    1.- Use @PostConstruct

    @PostContruct
    public void init() {
       this.str = "Anything";
    }
    

    2.- Use a simple request to set anything only

    @RequestMapping(value="/refresh/anythings", method = RequestMethod.PUT)
    public void refresh(@RequestBody(value = "str") String str) {
        this.str = str;
    }   
    

    3.- Use @Value

    In application.properties / application.yaml

    properties.str = anything    
    

    In the Controller

    @Value("${properties.str:default}") // by default str is "default"
    public String str;
    
    @RequestMapping(value="/greetings" , method = RequestMethod.GET)
    public String getGreetingFromDeu() {
        return this.str;
    }