【问题标题】:Exit Springboot from static function从静态函数中退出 Springboot
【发布时间】: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


【解决方案1】:

我不会尝试手动关闭应用程序,而是创建一个ApplicationRunner 来验证应用程序启动时的状态。如果抛出异常,应用程序将无法启动。例如:

@Component
public class SomeInitializer implements ApplicationRunner {

    private MyConfigValidator configValidator;

    // If it's a Spring bean, inject it
    public SomeInitializer(MyConfigValidator configValidator) {
        this.configValidator = configValidator;
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        if (!configValidator.isValid()) {
            throw new IllegalStateException("Some description");
        }
    }
}

此外,如果您想在启动时对配置属性执行验证,您可能需要考虑使用 @Validated @ConfigurationProperties bean:

@Validated
@ConfigurationProperties(prefix="some.prefix")
public class YourProperties {
    @NotEmpty
    private String someProperty;

    // getter and setter
}

有关使用经过验证的 ConfigurationProperties 的更多信息,请访问 here

【讨论】:

  • 不幸的是,使用注释进行验证非常有限,并且(据我所知)您无法执行验证业务规则,例如 (foo == false && bar >= 42)
  • 可以通过设置 ConstraintValidator bean 添加自定义验证。如果您需要基于多个字段(foo == x && bar==y)执行验证,请将验证放在类级别而不是字段级别。 Here 是一个验证器示例,用于验证 passwordconfirmPassword 字段是否匹配,类似于您的用例。
  • 如果 ConfigurationProperties 过于复杂,请改用 ApplicationRunner 示例。使用 @Value('${someProperty}') String someProperty 注入属性和/或自动装配 ApplicationContext 以访问其他 bean。
猜你喜欢
  • 1970-01-01
  • 2022-07-09
  • 1970-01-01
  • 2010-11-04
  • 2021-09-06
  • 2018-02-27
  • 2011-10-04
  • 1970-01-01
相关资源
最近更新 更多