Spring 引导@ConfigurationProperties未从外部属性文件或类路径属性文件加载



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

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

Package 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 引导弹簧批处理应用程序调用此代码时,此代码工作正常,该应用程序包含此库作为依赖项,并调用相应的 setter,当我在 application.properties 中添加job.schema=testSchema时,我可以看到模式集

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

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

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

@Value注释也适用于 Spring Boot,所以我想你可以进行更改,以便它适用于旧版本(Spring 3.x(,而新版本只需在不更改任何内容的情况下工作。

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

最新更新