如何在Spring的@Scheduled任务中构建URL?
问题描述:
我想建立到控制器方法的URL链接。我使用这种方法:如何在Spring的@Scheduled任务中构建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搜索并获得了一些变通方法,例如硬编码方案和主机来构建URL,但我不想对任何主机名进行硬编码,是否还有其他动态解决方案?
环境:
spring-boot-starter-web:jar:1.4.3.RELEASE
spring-webmvc:jar:4.3.2.RELEASE
答
不,你有计划的作业没有可用的要求,因为它不是由任何触发。恕我直言,你只有一个选择:
使用UriTemplate与你想在电子邮件中提供的链接模板,将参数值填入地图并展开它。基本URL应该保存在可配置的属性中。
其他方法(如使用链接构建器(例如Spring HATEOAS中包含的ControllerLinkBuilder))将失败,并具有相同的根本原因。
另外根据我的经验,唯一的方法是在可配置的属性中配置基础URL –