简体   繁体   English

如何在 Spring Boot 中使用 Enum 类返回验证消息?

[英]How to return validation message using Enum class in spring boot?

I am not asking "how to validate enums".我不是在问“如何验证枚举”。

Let's say I have request body like this one:假设我有这样的请求体:

public class VerifyAccountRequest {
    
    @Email(message = "2")
    private String email;
}

What i am trying to do, instead of hardcoded way, i just want to return message's value from enum class.我想要做什么,而不是硬编码的方式,我只想从枚举类返回消息的值。 But IDEA is saying "Attribute value must be constant"但 IDEA 说“属性值必须是常量”

public enum MyEnum {
    EMAIL("2", "info"),
    public String messageCode;
    public String info;
}

public class VerifyAccountRequest {
    
    @Email(message = MyEnum.Email.code) // NOT_WORKING
    private String email;
}

I can also define "2" in the interface, but i don't want to do that:我也可以在界面中定义“2”,但我不想这样做:

public interface MyConstant {
    String EMAIL = "2";
}

public class VerifyAccountRequest {
    
    @Email(message = MyConstant.EMAIL) // WORKS, BUT I HAVE TO USE ENUM !!!
    private String email;
}

is it possible to return message value using enum class ?是否可以使用枚举类返回消息值?

The Java rules say that when you have an annotation, and it has a parameter that expects a primitive type (such as an int) or a String, the value must be a constant expression. Java 规则规定,当您有一个注解,并且它有一个需要原始类型(例如 int)或 String 的参数时,该值必须是一个常量表达式。 You are trying to set a value on runtime.您正在尝试在运行时设置一个值。 However, annotation attributes must have an exact value before the JVM loads the class , it'll show an error otherwise.但是,在 JVM 加载类之前注释属性必须有一个确切的值,否则会显示错误。

The structure element_value can store values of four different types:结构 element_value 可以存储四种不同类型的值:

  1. a constant from the pool of constants来自常量池的常量
  2. a class literal类文字
  3. a nested annotation嵌套注释
  4. an array of values一组值

So, a constant from an annotation attribute is a compile-time constant.因此,注释属性中的常量是编译时常量。 Otherwise, the compiler wouldn't know what value it should put into the constant pool and use it as an annotation attribute.否则,编译器将不知道应该将什么值放入常量池并将其用作注释属性。 For more read this .欲了解更多信息,请阅读此内容

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM