我有一个 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 类:
@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();
}
}
我想在最终变量上使用@Value注释,该变量在注释@DateTimeFormat中使用。
@DateTimeFormat 需要一个最终的字符串变量,这就是为什么我需要在最终变量上使用@Value。但目前还不起作用。有什么想法吗?
最佳答案
我回答了这样的问题 https://stackoverflow.com/questions/7130425...
我会删除 static 修饰符并执行类似的操作:
@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 .
关于java - Spring MVC : @Value annotation with final variable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27955791/