简体   繁体   English

如果枚举验证失败,则阻止启动 spring-boot 应用程序

[英]Prevent to start spring-boot application if enum valitiation fails

I want to prevent my application from starting if my enum method for validation uniqueness of a field fails.如果用于验证字段唯一性的枚举方法失败,我想阻止我的应用程序启动。

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");
        }
    }
}

Just keep it simple.保持简单。 For example convert the verification to a static method:例如将验证转换为静态方法:

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");
    }
  }
}

Then you may implement InitializingBean in a bean and override the method afterPropertiesSet() .然后您可以在 bean 中实现InitializingBean并覆盖方法afterPropertiesSet() Eg suppose your application is called DemoApplication, it will look like this:例如,假设您的应用程序名为 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();
    }
}

From the documentation of InitializingBean :来自InitializingBean的文档:

Interface to be implemented by beans that need to react once all their properties have been set by a BeanFactory: eg to perform custom initialization, or merely to check that all mandatory properties have been set. BeanFactory 设置了所有属性后,需要由 bean 实现的接口:例如,执行自定义初始化,或仅检查是否已设置所有必需属性。

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

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