Spring:如何从属性文件中设置 @DateTimeFormat 的模式? [英] Spring: How do I set the pattern of a @DateTimeFormat from a properties file?
问题描述
我使用的是 Spring 3.1.1.RELEASE.我有一个模型,我提交给我的一个控制器.其中,是以下字段
I'm using Spring 3.1.1.RELEASE. I have a model that I submit to one of my controllers. In it, is the following field
@DateTimeFormat(pattern = "#{appProps['class.date.format']}")
private java.util.Date startDate;
但是,上面的方法不起作用(EL 没有被解释),因为每次我提交表单时,我都会收到一个错误.如果我使用以下
However, the above doesn't work (the EL isn't being interpreted), in as far as every time I submit my form, I get an error. If I use the following
@DateTimeFormat(pattern="yyyy-MM-dd")
private java.util.Date startDate;
一切正常.但理想情况下,我想从属性文件中驱动模式.这可能吗?如果可能,正确的语法是什么?
everything works fine. But ideally, I'd like to drive the pattern from a properties file. Is this possible and if so, what's the correct syntax?
- 戴夫
推荐答案
我会使用 PropertySourcesPlaceholderConfigurer 读取我的系统属性.然后你可以使用这个语法来解析占位符:${prop.name}
.
I would use PropertySourcesPlaceholderConfigurer to read my system properties. Then you can use this syntax to resolve placeholders : ${prop.name}
.
您的注释文件应该像这样工作:
Your annotated filed should work like this then:
@DateTimeFormat(pattern = "${class.date.format}")
private java.util.Date startDate;
要在 xml 中为您的应用程序配置 PropertySourcesPlaceholderConfigurer,请尝试以下操作:
To configure your PropertySourcesPlaceholderConfigurer for your application in xml, try this:
<bean class="org.springframework.beans.factory.config.PropertySourcesPlaceholderConfigurer">
<property name="location">
<list>
<value>classpath:myProps.properties</value>
</list>
</property>
<property name="ignoreUnresolveablePlaceholders" value="true"/>
</bean>
或者,使用 JavaConfig:
Or, with JavaConfig:
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
//note the static method! important!!
PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
Resource[] resources = new ClassPathResource[] { new ClassPathResource("myProps.properties")};
configurer.setLocations(resources);
configurer.setIgnoreUnresolvablePlaceholders(true);
return configurer;
}
这篇关于Spring:如何从属性文件中设置 @DateTimeFormat 的模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!