How to write Spring for external ports?
In Spring framework, you can define the exposed endpoints by writing a Controller class.
Firstly, in a Spring Boot project, create a Controller class and use the @RestController annotation to declare it as a controller. Also, use the @RequestMapping annotation to specify the root path of the controller.
@RestController
@RequestMapping("/api")
public class MyController {
@GetMapping("/hello")
public String hello() {
return "Hello, World!";
}
}
In the above example, the @GetMapping annotation indicates that the method handles an HTTP GET request with the path /api/hello. When a GET request is received, the hello() method is executed and returns the string “Hello, World!”.
Afterwards, run the Spring Boot application and access http://localhost:8080/api/hello to receive a response of “Hello, World!”.
By doing this, you have successfully created an exposed port. You can write more Controller classes and methods based on your own needs to handle different requests and business logic.