如何让 spring 启动控制器端点完整 url?
How to get spring boot controller endpoint full url?
如何在没有 concat/hardcode 字符串的情况下获得完整的 url 特定 spring 启动控制器端点?我的情况是需要向外部 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() {
...
}
}
如果您不想硬编码,可能的解决方案是在所有消息和 url 中添加一个 messages.properties。然后您可以配置 Spring MessageSource 并从该文件中获取您的 url。
假设您有一个 message.properties 文件,其中 属性:
url=full_url_to_your_service
在您的 @Controller
中,注入您配置的 MessageSource 以允许 Spring 解析消息:
@Autowired
private MessageSource messageSource;
然后你可以得到你的 url 如下:
String url= messageSource.getMessage("url", put_here_your_locale);
如果您需要更多信息,请查看 Spring doc MessageSource。
允许在您的系统上获取任何 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()
更改主机名等还有更多方法
如何在没有 concat/hardcode 字符串的情况下获得完整的 url 特定 spring 启动控制器端点?我的情况是需要向外部 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() {
...
}
}
如果您不想硬编码,可能的解决方案是在所有消息和 url 中添加一个 messages.properties。然后您可以配置 Spring MessageSource 并从该文件中获取您的 url。
假设您有一个 message.properties 文件,其中 属性:
url=full_url_to_your_service
在您的 @Controller
中,注入您配置的 MessageSource 以允许 Spring 解析消息:
@Autowired
private MessageSource messageSource;
然后你可以得到你的 url 如下:
String url= messageSource.getMessage("url", put_here_your_locale);
如果您需要更多信息,请查看 Spring doc MessageSource。
允许在您的系统上获取任何 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()
更改主机名等还有更多方法