Spring:如何从属性文件设置@DateTimeFormat 模式?

Bri*_*ace 5 java spring spring-mvc

我在这里提出同样的问题因为其中提供的答案不能解决我的问题。

我在 Spring MVC Web 应用程序中使用 Spring 4.1.3。我有一个包含该字段的 JPA 实体 bean:

@DateTimeFormat(pattern = "${date.format}")
private LocalDate certifiedOn;
Run Code Online (Sandbox Code Playgroud)

我希望基于属性文件中的键注入模式。 从 3.0.3 开始这应该在 Spring 中工作,但是控制器中的绑定失败,因为Pattern includes reserved character '{'.

我知道我正在成功读取我的属性文件,因为应用程序中正在使用其他属性。这是我通过 javaConfig 进行设置的方法:

@Configuration
@ComponentScan(basePackages = "com")
@PropertySource("classpath:spring.properties")
public class AppConfig {

  @Bean
  public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
    return new PropertySourcesPlaceholderConfigurer();
  }
  ...
}
Run Code Online (Sandbox Code Playgroud)

在类路径的根目录下有spring.properties文件:

date.format = yyyy-MM-dd
Run Code Online (Sandbox Code Playgroud)

我在这里缺少什么会阻止它工作?

Cug*_*uga 0

我尝试重现这个问题,你所做的一切看起来都是正确的——这就是我所拥有的:

应用程序属性

date.format=yyyy-MM-dd
Run Code Online (Sandbox Code Playgroud)

Spring管理的类

public class MyClass {
private static final Logger log = LoggerFactory.getLogger(MyClass.class);

@DateTimeFormat(pattern = "${yyyy-MM-dd}")
private LocalDate certifiedOn = LocalDate.now();

@Override
public void afterPropertiesSet() throws Exception {
    log.info("Date format used: " + certifiedOn);
}
}
Run Code Online (Sandbox Code Playgroud)

输出

使用的日期格式:2015-01-22

注意

我将该字段设置为LocalDate.now(),它以正确的格式显示日期。

如果我不设置该certifiedOn字段的值,则会打印出:

使用的日期格式:空

可能的原因

如果该null值是您在 中看到的值certifiedOn,则可能是date.format从属性文件中正确获取的,但只是尚未初始化为非空值。

否则,您在这里描述的所有内容都应该像广告中那样工作。除了您所看到的之外,也许还有另一个因素影响您正在经历的事情?