我有一个DTO。
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class CustomDTO {
@NotNull
@NotBlank
@Pattern(regexp = "[a-f0-9]{8}(?:-[a-f0-9]{4}){4}[a-f0-9]{8}", message = "waited pattern: '123e4567-e89b-12d3-a456-426655440000'")
private String documentId;
...
}
现在,我想使用SpringCloudConfig使其可配置。
在我的 .yml
文件中:
patterns:
document-id: "[a-f0-9]{8}(?:-[a-f0-9]{4}){4}[a-f0-9]{8}"
document-id-message: "waited pattern: '123e4567-e89b-12d3-a456-426655440000'"
我的配置类:
@Data
@Configuration
@ConfigurationProperties(prefix = "patterns")
public class PatternsConfiguration {
@NotNull
private String documentId;
@NotNull
private String documentIdMessage;
}
现在我的DTO将会是:
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class CustomDTO {
private final PatternsConfiguration patternsConfiguration; //Is it BAD Practice?
@NotNull
@NotBlank
@Pattern(regexp = patternsConfiguration.getDocumentId(), message = patternsConfiguration.getDocumentIdMessage())
private String documentId;
...
}
在 Spring Boot 的 DTO 中包含 @Configuration 类是一种不好的做法吗?
有趣的想法,但它让你失去了DTO的一个重要功能:< br >你不能再兑换你的DTO级。如果另一个java应用程序想要使用你的API,那么你可以给他们你的DTO类。简单。
现在将配置类连接到您的 DTO 会使这种共享过程非常烦人。版本控制也将更加困难。
下一件事:现代环境更多地使用接口定义语言(IDL ), open API非常受欢迎。< br >如果您想将您的API转换成IDL,那么当验证字段隐藏在configuration.yaml中时,会更加困难