How to pass an argument to a Spring Boot REST Controller?

霸气de小男生 提交于 2021-01-29 13:19:51

问题


I am trying to pass an argument to my @RESTController Spring Boot class.

In the @POSTMapping method I want to use a method of a self defined Java class for processing the received body and returning a response.

The Spring application is launched in Application.java. The Controller-Object seems to get created implicitly.

I already tried adding a constructor to my RESTController class. But I couldn't find a way to call that constructor with an argument.

// Application.java
public static void main (String[] args) {
    SpringApplication.run(Application.class, args);
}
//ConnectorService.java
@RestController
public class ConnectorService {

    private Solveable solver;

    public ConnectorService() {}

    public ConnectorService (Solveable solveable) {
        this.solver = solveable;
    }

    @CrossOrigin(origins = "http://localhost:3000")
    @PostMapping(path =  "/maze")
    public Solution Test(@RequestBody Test test) {
       return solver.solve(test);
    }

}

Even though i could define a second constructor, i didn't find any way to call it with my Object.


回答1:


Use @RequestParam annotation to pass an argument




回答2:


You can pass parameter with @RequestParam annotation like this:

@CrossOrigin(origins = "http://localhost:3000")
@PostMapping(path =  "/maze")
public Solution Test(@RequestParam("paramName") String param, @RequestBody Test test) {
   return solver.solve(test);
}

And you can put it with http request:

http://localhost:3000/maze?paramName=someValue

Assuming that you have POST request, there may be different ways to build this request, depending on the API testing tools you use.




回答3:


@RestController follows the same rules for dependency injection as any other @Component in Spring framework. If you have a single constructor, Spring will try to „inject” the parameters while instantiating the controller.

You need to register your dependency as a Spring bean.

It seems that you are new to Spring and you are starting with advanced topics like Spring Boot and rest controllers. Please find some time to read about the basics.




回答4:


Yo can create a Bean configuration file to initialize your objects like:

@Configuration
@ComponentScan("com.xxx.xxx") // the base package you want to scan
public class Config {

    @Bean
    //where Solveable is a class and is annotated with an Spring's annotation
    public Solveable solveable() {
        return new Solveable();
    }

}

And use the @Autowired annotation to inject the object in:

@Autowired    
public ConnectorService (Solveable solveable) {
      this.solver = solveable;
}

This last block will initialize or pass(what you want) the object to the ConnectorService class.



来源:https://stackoverflow.com/questions/58356927/how-to-pass-an-argument-to-a-spring-boot-rest-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!