java 如果枚举验证失败,则阻止启动Spring启动应用程序

46qrfjad  于 2022-12-21  发布在  Java
关注(0)|答案(1)|浏览(173)

如果验证字段唯一性的枚举方法失败,我希望阻止应用程序启动。

public enum MyEnum {
    VALUE_1(1),
    VALUE_2(1),    //same code as VALUE_1 is forbidden
    VALUE_3(3),
    ;

    private int code;

    static {    //this method is called only when 1st time acessing an inscance of this enum, I want it to be executed upon spring boot initialization and when it fails stop appliacation
        long uniqueCodesCount = Arrays.stream(MyEnum.values()).map(MyEnum::getCode)
                .distinct()
                .count();
        if (MyEnum.values().length != uniqueCodesCount) {
            throw new RuntimeException("Not unique codes");
        }
    }
}
p5cysglq

p5cysglq1#

只要保持简单就行了,例如将验证转换为静态方法:

public enum MyEnum {

  ...

  public static void verifyUniqueness() {
    long uniqueCodesCount = Arrays.stream(MyEnum.values()).map(MyEnum::getCode)
        .distinct()
        .count();
    if (MyEnum.values().length != uniqueCodesCount) {
      throw new RuntimeException("Not unique codes");
    }
  }
}

然后你可以在bean中实现InitializingBean并覆盖afterPropertiesSet()方法。例如,假设你的应用程序名为DemoApplication,它将如下所示:

@SpringBootApplication
public class DemoApplication implements InitializingBean {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        MyEnum.verifyUniqueness();
    }
}

来自InitializingBean的文档:

  • 由Bean实现的接口,这些Bean需要在BeanFactory设置其所有属性后做出React:例如,执行自定义初始化,或仅检查是否已设置所有强制属性。*

相关问题