Home > Mobile >  Prevent to start spring-boot application if enum valitiation fails
Prevent to start spring-boot application if enum valitiation fails

Time:12-20

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

CodePudding user response:

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(). E.g. suppose your application is called DemoApplication, it will look like this:

@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:

Interface to be implemented by beans that need to react once all their properties have been set by a BeanFactory: e.g. to perform custom initialization, or merely to check that all mandatory properties have been set.

  • Related