【问题标题】:Spring boot @ConfigurationProperties not loading from external properties file or class path property fileSpring boot @ConfigurationProperties 未从外部属性文件或类路径属性文件加载
【发布时间】:2019-03-04 21:54:33
【问题描述】:

您好,我正在尝试使用我使用 spring boot(2.0.5) 从 2 个应用程序创建的可重用库我能够将我的类路径中的 application.properties 中的属性绑定到我的 bean,如下所示,我看到在我的第一个 spring 批处理应用程序中通过我的调试中的设置器设置模式,该应用程序也是使用 spring boot(2.0.5) 创建的

这是我的库中的属性 bean 类,它包含一些服务 api-这个库只是一个使用 spring boot 创建的 jar 包。

包 com.test.lib.config

@ConfigurationProperties("job")

@PropertySources({

@PropertySource(value = "${ext.prop.dir}", ignoreResourceNotFound = true),

@PropertySource(value = "classpath:application.properties", ignoreResourceNotFound = true)

})

public class ServiceProperties {

           /**

           * Schema for the service

           */

           private String schema;


public String getSchema() {

                          return schema;

           }

           public void setSchema(String schema) {

                          this.schema = schema;
           }

}

这个库的配置bean如下在同一个包中。

@Configuration

@EnableConfigurationProperties(ServiceProperties.class)

@ComponentScan("com.test.lib")

 public class LibraryModuleConfig {
 }

当从包含此库作为依赖项的 sprint 启动 spring 批处理应用程序调用时,此代码工作得非常好,并且调用了相应的 setter,当我在 application.properties 中添加 job.schema=testSchema 时,我可以看到架构集

我尝试在现有的 spring mvc web 应用程序中使用这个相同的库,该应用程序从一个 tomcat 服务器启动,外部文件目录作为启动参数(这个应用程序不是用 spring boot 创建的)并添加了适当的 context:component-scan 以包含应用程序上下文(appn-context.xml)中库中的bean(java配置bean)。 job.schema 属性是从 application.properties 文件甚至 C 驱动器中的外部文件传递的,由 @propertySources 注释中的 ${ext.prop.dir}" 给出。ServiceProperties Bean 中的模式属性永远不会被设置和甚至setter也不会在调试中被调用。为什么这个libray config bean不能在现有的spring mvc应用程序中工作,但可以与spring批处理应用程序一起工作。他们都将库作为依赖项添加。我已经做了很长时间了时间,除了 spring 属性绑定之外,其他功能似乎都可以工作。

【问题讨论】:

    标签: spring spring-boot properties


    【解决方案1】:

    @EnableConfigurationProperties 是 Spring Boot 提供的一个方便的注解。 (Spring MVC 默认不提供)

    对于旧版 Spring MVC 应用程序(特别是 Spring 3.x),您可以对属性使用 @Value 注释。

    @Value 注释也适用于 Spring Boot,所以我想您可以进行更改以使其适用于旧版本(Spring 3.x),而新版本则无需更改任何内容即可运行。

    希望这会有所帮助!快乐编码:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-05
      • 2014-12-16
      • 2018-12-19
      • 2020-07-30
      • 2015-05-14
      • 1970-01-01
      • 2018-06-25
      相关资源
      最近更新 更多