我有一个 bean 定义如下:
public class PostDTO {
@Autowired
private Messages messages;
private String id;
@Size(min = Constant.POST_TITLE_MIN_LEN, max = Constant.POST_TITLE_MAX_LEN, message = messages.get("post.err.title"))
private String title;
}
我想要message
值根据区域设置是动态的。上面的代码显示The value for annotation attribute Size.message must be a constant expression
错误。
最佳答案
我认为你可以使用 SpEL(Spring 表达式语言)
public class PostDTO {
private String id;
@Size(min = Constant.POST_TITLE_MIN_LEN, max = Constant.POST_TITLE_MAX_LEN, message = "#{'${post.err.title}'}")
private String title;
}
并在 spring 属性文件中定义变量,如下所示:
post.err.title = “发布错误”
SpEL 的更多详细信息:https://docs.spring.io/spring/docs/4.3.10.RELEASE/spring-framework-reference/html/expressions.html
关于java - 在 Spring 中动态设置 Java bean 验证消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58195049/