Spring Boot-如果未设置属性,则检测并终止? [英] Spring Boot - Detect and terminate if property not set?

查看:142
本文介绍了Spring Boot-如果未设置属性,则检测并终止?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果未在任何地方设置必需的属性(在application.properties文件或其他属性源中均未设置),Spring Boot Web应用程序是否有任何方法在启动时中止?现在,如果该属性包含在另一个属性中,则看来Spring Boot只是避免了替换.

Is there any way for a Spring Boot web application to abort at startup if a required property is not set anywhere (neither in the application.properties file nor the other property sources)? Right now, if the property is included in another property, it seem that Spring Boot simply avoids substitution.

例如,在我的application.properties文件中,有以下一行:

For example, in my application.properties file, I have the line:

quartz.datasource.url=jdbc:hsqldb:${my.home}/database/my-jobstore

现在,如果未在其他位置设置"my.home",则Spring Boot会将字面值设置为"jdbc:hsqldb:$ {my.home}/database/my-jobstore" (无替代).

Right now, if "my.home" is not set elsewhere, Spring Boot is setting the url literally to "jdbc:hsqldb:${my.home}/database/my-jobstore" (no substitution).

如果未在其他任何地方设置属性my.home,我希望应用程序无法启动.

I would like to have the application fail to start if the property my.home were not set anywhere else.

推荐答案

使用带@Value(${my.home})注释的简单字段创建一个bean. -然后,Spring将尝试注入该值,并且将失败并因此在该值不存在时停止.

Create a bean with a simple @Value(${my.home}) annotated field. - Then Spring will try to inject that value and will fail and therefore stop when the value is not there.

@Value(${my.home}) private String myHomeValue;就足够用于常规(而非Boot)Spring应用程序了!但是我不知道,Boot是否具有其他配置来处理丢失的值:如果存在其他故障管理,则可以在PostCreation方法中检查该值.

Just @Value(${my.home}) private String myHomeValue; is enough for normal (not Boot) Spring applications for sure! But I do not know whether Boot has some other configuration to handle missing values: If there is an other failure management than you could check that value in an PostCreation method.

@Component
public static class ConfigurationGuard implements InitializingBean {

   @Value(${my.home})
   private String myHomeValue;

   /**
    * ONLY needed if there is some crude default handling for missing values!!!!
    *
    * So try it first without this method (and without implements InitializingBean)
    */
   public void afterPropertiesSet() {
      if (this.myHomeValue == null or this.myHomeValue.equals("${my.home}") {
          throw new IllegalArgumentException("${my.home} must be configured");
      }
   }

}

这篇关于Spring Boot-如果未设置属性,则检测并终止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆