【发布时间】:2021-01-21 14:57:48
【问题描述】:
在我的 Springboot 应用程序中,我使用“实用程序”类(只有静态方法的类) 来验证我的配置上的业务规则。
例如
@Component
public class MyClass {
@Autowired
public MyClass(MyConfig config) {
MyConfigValidator.validate(config);
}
...
如果MyConfigValidator.validate()发现配置不一致,就不得不退出Springboot应用
据我所知,正确退出 Springboot 应用程序的最佳/唯一方法是运行:
SpringApplication.exit(context, () -> returnCode);
context 是一个ApplicationContext 实例必须注入。
我的问题来自static 方法MyConfigValidator.validate():是静态的,它无法访问注入的值
我们来看看MyConfigValidator:
public class MyConfigValidator {
public static void validate(MyConfig config) {
if (!isValid(config)) {
doExit();
}
}
/// no need to detail here the isValid() method
private static void doExit() {
/// here, I don't know how to get the applicationContext
SpringApplication.exit(applicationContext, () -> returnCode);
}
}
你知道我如何在我的MyConfigValidator 课程中获得ApplicationContext。
谢谢你的帮助
问候, 菲利普
【问题讨论】:
-
我能想到的唯一方法是将上下文作为参数传递给 doExit()
-
我不确定为什么您的配置验证器首先是静态的。
标签: java spring spring-boot exit shutdown