如何在Spring的@Scheduled任务中构建URL?

时间:2016-12-26 10:49:21

标签: spring spring-mvc spring-boot

我想建立到Controller方法的URL链接。我用这个方法:

URI uri = MvcUriComponentsBuilder.fromMethodCall
(on(MyController.class).myMethod(...))
.build().encode().toUri();

生成URL(例如,定期发送包含链接的电子邮件)。

问题是,当在Spring的@Scheduled任务中运行时,它无法获得RequestContext,因此会抛出此异常:

java.lang.IllegalStateException: Could not find current request via RequestContextHolder
    at org.springframework.util.Assert.state(Assert.java:392)
    at org.springframework.web.servlet.support.ServletUriComponentsBuilder.getCurrentRequest(ServletUriComponentsBuilder.java:190)
    at org.springframework.web.servlet.support.ServletUriComponentsBuilder.fromCurrentServletMapping(ServletUriComponentsBuilder.java:166)
    at org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder.getBaseUrlToUse(MvcUriComponentsBuilder.java:412)

如果在测试环境中,这可以通过注入MockHttpServletRequest来解决,但它不起作用,因为它不在环境中。

如何解决?

我用Google搜索并获得了一些解决方案,例如硬编码方案和主机来构建网址,但我不想对任何主机名进行硬编码,还有其他动态解决方案吗?

环境:

spring-boot-starter-web:jar:1.4.3.RELEASE
spring-webmvc:jar:4.3.2.RELEASE

1 个答案:

答案 0 :(得分:1)

不,您在预定作业中没有可用的请求,因为它没有被任何触发。恕我直言,你只有一个选择:

UriTemplate与您希望在电子邮件中提供的链接模板一起使用,将参数值填入地图并展开。基本URL应保存在可配置属性中。

使用链接构建器(例如ControllerLinkBuilder中包含的Spring HATEOAS)等其他方法将因相同的根本原因而失败。