如何在dto类的注释中导入application.yml属性



Application.yml

datetime:
format: yyyy/MM/dd HH:mm:ss

transaction.java

@Entity
@Getter
@Setter
@NoArgsConstructor
public class Transaction{
@Id
@NotNull
@Enumerated(EnumType.STRING)
private TransactionSourceEnum transactionSource;
@Id
@NotNull
@Column(unique = true)
private String transactionId;
private String responseCode;
private String failureReason;
@NotNull
@JsonFormat(pattern = "yyyy/MM/dd HH:mm:ss")
private Date transactionCreSysDate;
}

我试过这个

@JsonFormat(pattern = "${datetime.format}")

这行不通。我想用datetime.format 替换JsonFormat模式

当我遇到同样的问题时,我只定义了一个全局变量public static String date = "yyyy/MM/dd HH:mm:ss";

更改模式以使用全局变量@JsonFormat(pattern = Classname.date)

它确实对我有用。

真正的解决方案是在配置ObjectMapper时使用该属性。

在春季,最简单的方法是为属性定义值

spring.jackson.date-format=${datetime.format}

此解决方案的主要缺点是,它只允许为每个应用程序配置一种日期格式。因为,正如您所指出的,不可能在@JsonFormat注释中使用SPEL。而且在注释参数中也不可能使用非常量字段。我认为没有一个简单的解决方案可以允许使用配置属性配置日期格式。

试试这个:

@Value("${datetime.format}")
private String dateFormat;
@JsonFormat(pattern = dateFormat)

相关内容

最新更新