java - 如何在配置过程中关闭 Spring 应用程序?
问题描述
在配置过程中或在应用程序上下文初始化之后关闭 Spring 应用程序的最佳实践是什么?
例如,在我的情况下,我有几个@ConfigurationProperties
,并且必须指定其中至少一个,否则应用程序将关闭。我应该使用@Conditional
, 一些通用@ConfigurationProperties
的验证,还是别的什么?
我决定将验证与一般@ConfigurationProperties
@Constraint(validatedBy = AtLeastOneOfTheFieldsValidator.class)
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface AtLeastOneOfTheFields {
String message() default "At least one of the fields must be specified";
String onBooleanCondition();
String[] fields();
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
@interface List {
AtLeastOneOfTheFields[] value();
}
}
public class AtLeastOneOfTheFieldsValidator implements ConstraintValidator<AtLeastOneOfTheFields, Object> {
private String[] fields;
private String booleanConditionField;
@Override
public void initialize(AtLeastOneOfTheFields atLeastOneOfTheFields) {
this.fields = atLeastOneOfTheFields.fields();
this.booleanConditionField = atLeastOneOfTheFields.onBooleanCondition();
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
Object booleanConditionValue = new BeanWrapperImpl(value).getPropertyValue(booleanConditionField);
if (Objects.isNull(booleanConditionValue) || Objects.equals(Boolean.TRUE, booleanConditionValue)) {
return Arrays.stream(fields)
.map(field -> new BeanWrapperImpl(value).getPropertyValue(field))
.anyMatch(Objects::nonNull);
}
return true;
}
}
@Getter
@Setter
@Configuration
@ConfigurationProperties(prefix = "bot")
@Validated
@AtLeastOneOfTheFields(fields = {"facebook.page-access-token", "telegram.token", "viber.token"},
onBooleanCondition = "enabled",
message = "At leas one of bot token must be specified if property bot.enabled = 'true'.")
public class BotConfig {
@NotNull
private Boolean enabled;
@NestedConfigurationProperty
private FacebookBotConfig facebook;
@NestedConfigurationProperty
private TelegramBotConfig telegram;
@NestedConfigurationProperty
private ViberBotConfig viber;
}
另一个变体ApplicationContextInitializer
用于验证环境属性。
我会很高兴收到您的意见或建议。=)
解决方案
您可以像这样创建一些关闭处理程序组件:
@Component
public class ShutdownHandler {
@Autowired
private ApplicationContext applicationContext;
public void shutdown(int code) { // to shutdown you have to put 0 number
SpringApplication.exit(applicationContext, () -> code);
}
}
在你的属性类上,调用它;
@ConfigurationProperties
public class ConfigProperties {
@Autowired
private ShutdownHandler handler;
public void someMethod() {
if (isValid){
handler.shutdown(0);
}
}
}
推荐阅读
- swiper - Swiper Js - 无法从图像帖子中删除覆盖线性背景
- assembly - 更改后要打印内存中的原始值
- javascript - 我有一个 HTML 表单,它使用 POST 请求和 PHP 文件自动向我发送电子邮件,但它不起作用……有什么建议吗?
- database - MongoDB传感器存储策略
- vector - 为什么模拟时会得到未定义的输出向量和未定义的时钟?
- rust - 在 Rust 中实现读取行或睡眠定时器有哪些好方法
- firebase - 无法将某些特定子域用于 firebase 动态链接
- spring-boot - 将 spring-actuator 与 Spring-Boot 默认 Docker-Image 构建器一起使用
- twilio - 即将推出的 A2P 10DLC 变更,每月 10 美元/每项活动费用
- git - 将 Notepad++ 设置为提交的默认 Git 编辑器时出现错误