【问题标题】:Spring MVC: @Value annotation with final variableSpring MVC:带有最终变量的@Value注释
【发布时间】:2015-03-13 09:29:02
【问题描述】:

我有一个 config.properties 文件:

date_format="yyyy-MM-dd"

我的springmvc-servlet.xml:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>classpath:config/config.properties</value>
        </list>
    </property>
</bean>

这是我的控制器类:

@Controller
@RequestMapping("/T")
public class Test extends BaseController
{
    @Value("${date_format}")
    private static final String format; // Here, I want a final String as a constant

    @RequestMapping(value = "t2")
    @ResponseBody
    public String func(@RequestParam("date") @DateTimeFormat(pattern = format) Date date)
    {
        return date.toString();
    }
}

我想在一个final变量上使用@Value注解,这个注解用在@DateTimeFormat注解中。

@DateTimeFormat 需要一个最终的字符串变量,这就是我需要在最终变量上使用@Value 的原因。但它目前不起作用。有什么想法吗?

【问题讨论】:

  • 您的日期格式是否经常变化,以至于您需要在属性文件中对其进行配置?
  • 为什么要注入静态字段?请参阅stackoverflow.com/questions/10938529/… 了解不这样做的原因。

标签: java spring spring-mvc servlets


【解决方案1】:

我回答了这样的问题 https://stackoverflow.com/questions/7130425...

我会删除静态修饰符并执行类似的操作:

@Controller
@RequestMapping("/T")
public class Test extends BaseController{

   @Value("${date_format}")
   private final String format; // Removed static

   public Test (@Value("${date_format}") format){
     this.format = format;
   }

   @RequestMapping(value = "t2")
   @ResponseBody
   public String func(@RequestParam("date") @DateTimeFormat(pattern = format) Date date){
     return date.toString();
   }
}

这被称为Constructor Injection

【讨论】:

    猜你喜欢
    • 2021-11-20
    • 2020-02-25
    • 1970-01-01
    • 2010-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多