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

标签 java spring spring-mvc

我提出了同样的问题 here因为其中提供的答案无法解决我的问题。

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

@DateTimeFormat(pattern = "${date.format}")
private LocalDate certifiedOn;

我希望根据属性文件中的键注入(inject)模式。 This should work in Spring since 3.0.3 ,但是绑定(bind)在 Controller 中失败,因为 Pattern 包含保留字符“{”

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

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

  @Bean
  public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
    return new PropertySourcesPlaceholderConfigurer();
  }
  ...
}

spring.properties 文件位于类路径的根目录下:

date.format = yyyy-MM-dd

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

最佳答案

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

application.properties

date.format=yyyy-MM-dd

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);
}
}

输出

Date format used: 2015-01-22

注意事项

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

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

Date format used: null

可能的原因

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

否则,您在此处描述的所有内容都应该像宣传的那样有效。也许除了你所看到的之外,还有另一个因素会影响你的体验?

关于java - Spring:如何从属性文件中设置@DateTimeFormat 模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27537093/

相关文章:

java - 如何在android中使用java制作ImageView?

java - Spring AOP 为什么需要代理类?

java - 如何声明一个具有以 String 和 Map 作为参数的构造函数的 bean?

java - Spring Config Server 是否有可能从自身获取配置?

java - 从非事务方法调用的多个事务方法的传播级别

JavaScript 提交按钮从 Spring MVC 返回对象响应

java - 结合 DispatcherServlet、ContextLoaderListener 和 SpringSecurity

java - Spring MVC 中的 500 错误处理

java - Clojure - 消耗的惰性序列元素是否保留在内存中?

java - 使用 Jackson 通过 AJAX 从 Spring MVC Controller 返回 java.util.List