@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


问题答案:

我也遇到了这个问题,并在意识到没有将PropertyPlaceholderConfigurerbean加载到存在许多占位符的模块的上下文中后就解决了这个问题。

一个简单的解决方案是重构我们的外部化配置。最后,我将@PropertySources定义和PropertyPlaceholderConfigurerbean移到了一个通用模块,一切顺利:

@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)