2016-12-26 85 views
0

我想建立到控制器方法的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 

回答

1

不,你有計劃的作業沒有可用的要求,因爲它不是由任何觸發。恕我直言,你只有一個選擇:

使用UriTemplate與你想在電子郵件中提供的鏈接模板,將參數值填入地圖並展開它。基本URL應該保存在可配置的屬性中。

其他方法(如使用鏈接構建器(例如Spring HATEOAS中包含的ControllerLinkBuilder))將失敗,並具有相同的根本原因。

+0

另外根據我的經驗,唯一的方法是在可配置的屬性中配置基礎URL –

相關問題