【问题标题】:@RequestMapping with placeholder not working带有占位符的@RequestMapping 不起作用
【发布时间】:2014-06-17 05:45:26
【问题描述】:

所以我花了几个小时试图让这篇文章的anwser工作:
Overriding RequestMapping on SpringMVC controller

但它确实不起作用。到目前为止我所拥有的:

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

这应该可以正常工作。当我调用该页面时,我收到一条日志消息,上面写着“测试:myUrl” .但!这在我调用“/${requestmapping.test},html”时出现。它应该与调用“/myUrl.html”一起使用。我完全不知道为什么会这样。显然,PropertyPlaceholder 可以工作,但不能同时工作。 (顺便说一句:它是一个嵌套的 RequestMapping。但它也不适用于 topLvl-RequestMapping)

这是怎么回事?我该怎么做才能解决这个问题?我目前正在使用 spring verion 3.2.8

【问题讨论】:

  • @RequestMapping 中有 EL 吗?我以前从未见过这个,所以如果是的话,这对我来说是新的。
  • 我不是说你错了,我只是很惊讶这能奏效。我知道您可以使用{...}@PathVariables 放置占位符,甚至知道那些可以使用正则表达式。我想我只是从未读过说您可以使用 EL 在@RequestMapping 中插入属性值的部分。 Spring 人员在他们的 api 中投入的详细程度总是让我感到惊讶。

标签: spring-mvc


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2016-10-27
    • 2021-02-08
    • 2015-03-20
    • 2012-09-22
    • 1970-01-01
    • 1970-01-01
    • 2013-09-28
    • 1970-01-01
    • 2014-03-04
    相关资源
    最近更新 更多