2014-04-30 51 views
1

所以我必須花時間去嘗試得到這一職位的工作的anwser:
Overriding RequestMapping on SpringMVC controller@RequestMapping與佔位符不工作

但它確實是不工作。我至今:

用SpringMVC-servlet.xml中

<context:property-placeholder location="classpath:numbernick.properties"/> 
<context:component-scan base-package="com.numbernick" /> 
<context:annotation-config /> 

而且我有一個控制器:

@Value("${requestmapping.test}") 
private String test; 

@RequestMapping("${requestmapping.test}.html") 
public ModelAndView test() { 
    ModelAndView mav = new ModelAndView(); 
    mav.setViewName(test.html); 

    log.debug("Test: "+test); 
    return mav; 
} 

numbernick.properties:

requestmapping.test=myUrl 

這應該工作正常。當我打電話給我的網頁時,我收到了一條名爲「Test:myUrl」的記錄短信。但!這是當我打電話「/${requestmapping.test},html」。它應該調用「/myUrl.html」。我完全不知道爲什麼這樣。很顯然,PropertyPlaceholder可以工作,並且不能同時工作。 (順便說一句:它是一個嵌套的RequestMapping,但它也不能在topLvl-RequestMapping中工作)

這怎麼可能,我該怎麼辦才能解決這個問題?我目前正在使用spring verion 3.2.8

+0

EL是在@ @ RequestMapping中的一件事情嗎?我從來沒有見過這種情況,如果是這樣,這對我來說是新的。 – CodeChimp

+0

那麼這是如何在文檔中:http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-requestmapping-placeholders – Numbernick

+0

我wasn不是說你錯了,我只是感到驚訝,這工作。我知道你可以使用'{...}'作爲'@ PathVariable'的佔位符,甚至可以使用正則表達式。我想我從來沒有讀過那些說你可以用EL在你的'@ RequestMapping'中使用屬性值的部分。它永遠不會讓我驚訝於春天的人們把他們的細節放在他們的api上。 – CodeChimp

回答

1

我還遇到過這個問題,並且在我意識到PropertyPlaceholderConfigurer bean未加載到存在許多佔位符的模塊上下文中時解決了它。

簡單的解決方案是重構我們的外部化配置。最後,我搬到了@PropertySources定義和PropertyPlaceholderConfigurer豆到一個通用模塊,一切都很好:

@Configuration 
@PropertySources(value = {@PropertySource("classpath:app-config.properties")}) 
public class ExternalizedConfig { 

@Bean 
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { 
    return new PropertySourcesPlaceholderConfigurer(); 
} 

請求映射喜歡這項工作目前預計:

@RequestMapping(value="/${foo.bar.rest_proxy_uri}/**", method = RequestMethod.GET) 

事實上,在服務器啓動時,你會看到佔位符已經被解析:

2015-05-06 16:21:52 INFO RequestMappingHandlerMapping:220 - Mapped "{[/restProxy/**],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.http.ResponseEntity<java.lang.String> foo.bar.web.controllers.RestfulFooBarProxyController.proxyGet(javax.servlet.http.HttpServletRequest)