【问题标题】:How to get spring boot controller endpoint full url?如何获取 Spring Boot 控制器端点完整 url?
【发布时间】:2018-01-04 01:04:31
【问题描述】:

如何在没有 concat/hardcode 字符串的情况下获取特定的 Spring Boot 控制器端点完整 url?我的情况是需要向外部 url 发送请求并从中获取异步通知,因此我需要将通知端点完整 url 传递给它。这是示例代码:

    @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() {
          ...
       }
    }

【问题讨论】:

    标签: spring url spring-boot controller endpoint


    【解决方案1】:

    如果您不想要硬编码,可能的解决方案是添加带有所有消息和网址的 messages.properties。然后您可以配置 Spring MessageSource 并从该文件中获取您的 url。

    假设您有一个带有以下属性的 message.properties 文件:

    url=full_url_to_your_service
    

    在您的 @Controller 中,注入您配置的 MessageSource 以允许 Spring 解析消息:

     @Autowired
     private MessageSource messageSource;
    

    然后你可以得到你的网址如下:

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

    如果您需要更多信息,请查看 Spring doc 获取 MessageSource。

    【讨论】:

      【解决方案2】:

      允许获取系统上的任何 URL,而不仅仅是当前的。

      import org.springframework.hateoas.mvc.ControllerLinkBuilder
      ...
      ControllerLinkBuilder linkBuilder = ControllerLinkBuilder.linkTo(methodOn(YourController.class).getSomeEntityMethod(parameterId, parameterTwoId))
      
      URI methodUri = linkBuilder.Uri()
      String methodUrl = methodUri.getPath()
      

      还有更多方法可以更改主机名等。

      【讨论】:

      • @Cyva 它提供了 LAN ip。有什么方法可以使用 hatoas 获取公共 URL
      猜你喜欢
      • 2022-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-09
      • 1970-01-01
      相关资源
      最近更新 更多