【问题标题】:Set the Java bean validation message dynamically in Spring [duplicate]在Spring中动态设置Java bean验证消息[重复]
【发布时间】:2019-10-02 12:47:10
【问题描述】:

我有一个 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 错误。

【问题讨论】:

  • 我可以知道你为什么在 EntityClass 中使用@Autowired 吗?

标签: java spring spring-boot


【解决方案1】:

我认为你可以使用 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 = “Post Error”

SpEL 的更多详情:https://docs.spring.io/spring/docs/4.3.10.RELEASE/spring-framework-reference/html/expressions.html

【讨论】:

  • 它不起作用
猜你喜欢
  • 1970-01-01
  • 2014-02-24
  • 2020-05-26
  • 1970-01-01
  • 2013-04-14
  • 1970-01-01
  • 2013-11-19
  • 2011-05-11
  • 1970-01-01
相关资源
最近更新 更多