问题
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;
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?
- Dave
回答1:
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;
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>
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;
}
回答2:
Right now it seems only to work with Property Placeholders.
Have a look at this: https://jira.springsource.org/browse/SPR-8654
来源:https://stackoverflow.com/questions/17979137/spring-how-do-i-set-the-pattern-of-a-datetimeformat-from-a-properties-file