Spring: How do I set the pattern of a @DateTimeFormat from a properties file?

China☆狼群 提交于 2019-12-11 00:13:23

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!