【问题标题】:Don't fail if @Value is not supplied in properties?如果属性中没有提供@Value,不要失败?
【发布时间】:2019-04-05 23:44:34
【问题描述】:

我导入了一个依赖项,该依赖项具有一些带有@Value 字段的服务。在我的 Spring Boot 应用程序中,我不使用这些服务,但我仍然使用此依赖项中的一些其他类,现在如果我运行我的应用程序,它将失败,因为它无法解析占位符,例如

原因:java.lang.IllegalArgumentException:无法解析 占位符“apn.authentication.token.teamId”的值 "${apn.authentication.token.teamId}"

所以要解决这个问题,我必须在我的属性中定义值。我搜索了一个设置,让我的应用不会因未知值而失败,但我找不到方法。

有没有办法让我的 Spring Boot 应用启动,即使有缺失值?或者我应该排除我不使用的类(以及如果这是唯一的选择怎么办)?

【问题讨论】:

    标签: java spring spring-mvc spring-boot


    【解决方案1】:

    您可以设置一些默认值,以便如果该值不存在,则采用默认值

    @Value("${apn.authentication.token.teamId:-99}")
    private int teamId;
    

    或 将值设置为空

    @Value("${apn.authentication.token.teamId:#{null}}")
    private Integer teamId;
    

    【讨论】:

    • 知道如何为类路径资源值配置它吗?例如@Value("classpath:APNsAuthKey.p8") 如果我在 @Value("classpath:APNsAuthKey.p8:#{null}") 这样的扩展名之后添加 :#{null} 它不起作用,spring 认为文件名应该是 APNsAuthKey.p8:(注意冒号)。
    • 其实我觉得资源值不是默认值,所以我把它改成@Value("classpath:APNsAuthKey.p8") private Resource apnsCertificate;并在资源上处理getInputStream()
    • 有多种方法可以做到这一点 1) 在 application.properties 中添加 2) 使用 -DAPNsAuthKey.p8= 作为命令行参数。
    【解决方案2】:

    您可以将 PropertySourcesPlaceholderConfigurer 配置为不会在未知占位符上失败:

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
        propertySourcesPlaceholderConfigurer.setIgnoreUnresolvablePlaceholders(true);
        return propertySourcesPlaceholderConfigurer;
    }
    

    它不会失败,也不会费心去解决它。一般来说,在未知属性上失败(它们是属性,因为您的应用程序需要它们才能运行)或添加它们的默认值是一个很好的做法。如果您的配置对您的应用程序运行而言并不重要,您可以创建一个额外的配置文件并在运行时读取它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-13
      • 2022-10-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多