Spring Boot - 如果未设置属性,则检测并终止?

标签 spring spring-boot

如果未在任何地方设置所需属性(无论是在 application.properties 文件还是其他属性源中),Spring Boot Web 应用程序是否有任何方法可以在启动时中止?现在,如果该属性包含在另一个属性中,Spring Boot 似乎只是避免了替换。

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

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

现在,如果“my.home”未在其他地方设置,Spring Boot 会将 url 按字面意思设置为“jdbc:hsqldb:${my.home}/database/my-jobstore” (无替代)。

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

最佳答案

要抛出友好的异常,只需在属性中放置默认的 null 值,然后在 afterProperty 方法中检查并抛出异常。

@Component
public static class ConfigurationGuard implements InitializingBean {

@Value("${my.home:#{null}}")
private String myHomeValue;

public void afterPropertiesSet() {
    if (this.myHomeValue == null or this.myHomeValue.equals("${my.home}") {
          throw new IllegalArgumentException("${my.home} must be configured");
    }
 }
}

关于Spring Boot - 如果未设置属性,则检测并终止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31528697/

相关文章:

java - Spring security Role 无法转换为授权权限

java - Spring Boot APP - 单元测试

java - 带有 Spring 引导的 JUnit 5 - 如何使用不同的配置文件重复测试?

intellij-idea - Intellij 14.1.4 CE spring boot 1.3.0.M1,spring-dev-tools 热重载不工作

测试中的 Spring bean

java - Spring 安全: how to change user roles without login and logout

java - 如何转换 java.util.Map<String, Object> 中的 google.protobuf.Struct 字段?

java - 动态更改 spring.properties 中的属性而无需重建 .war?

mysql - 如何在Spring Boot中使用实体解决SQL语法错误?

spring - 如何使用 application.properties 传递 Map<String, String>