1

How to get a specific spring boot controller endpoint full url without concat/hardcode strings? My case is need send a request to external url and get async notification back from it, so I need pass my notification endpoint full url to it. Here is sample code:

    @RestController
    @RequestMapping("/api/v1")
    public class MyController {

       @PostMapping("/sendRequest")
       public void sendRequest() {
          ...
          // 1. get /notifyStatus endpoint full url to be send to external service
          String myNotificationFullUrl = xxx ?
          // 2. call external service
       }

       @GetMapping("/notifyStatus")
       public void notifyStatus() {
          ...
       }
    }
Michael Petch
  • 46,082
  • 8
  • 107
  • 198
Casel Chen
  • 497
  • 2
  • 8
  • 19

2 Answers2

0

Allows getting any URL on your system, not just a current one.

import org.springframework.hateoas.mvc.ControllerLinkBuilder
...
ControllerLinkBuilder linkBuilder = ControllerLinkBuilder.linkTo(methodOn(YourController.class).getSomeEntityMethod(parameterId, parameterTwoId))

URI methodUri = linkBuilder.Uri()
String methodUrl = methodUri.getPath()

There are more methods also to change a host name, etc.

Cyva
  • 1,057
  • 10
  • 9
-1

if you don't want hardcode, maybe a possible solution is add a messages.properties with all your messages and urls. Then you can configure Spring MessageSource and get your url from that file.

Supose that you have a message.properties file with the following property:

url=full_url_to_your_service

In your @Controller, inject your configured MessageSource to allow Spring resolve the messages:

 @Autowired
 private MessageSource messageSource;

Then you can get your url as follow:

String url= messageSource.getMessage("url", put_here_your_locale);

If you need more information, check Spring doc for MessageSource.

Antonio314
  • 61
  • 6