如果验证字段唯一性的枚举方法失败,我希望阻止应用程序启动。
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");
}
}
}
1条答案
按热度按时间p5cysglq1#
只要保持简单就行了,例如将验证转换为静态方法:
然后你可以在bean中实现
InitializingBean
并覆盖afterPropertiesSet()
方法。例如,假设你的应用程序名为DemoApplication,它将如下所示:来自
InitializingBean
的文档: