首页 > 解决方案 > Springboot application.properties 文件无法使用默认和自定义属性

问题描述

所以我几乎遵循了所有教程/示例和堆栈溢出问题,但我似乎仍然无法让我的 application.properties 文件能够在我创建的 ExternalConfig 类中填写值。

我的应用程序属性类文件位于 src/main/resources 中,如下所示

app.developerName = "f21ad267-e241-4ed0-8943-721fa90bcf3a"
spring.boot.config.developerName = "f21ad267-e241-4ed0-8943-721fa90bcf3a"
server.port=9000
Access-Control-Allow-Origin: *

我专门构建的外部配置类看起来像这样

@ConfigurationProperties(prefix="spring.boot.config")
@Component
public class ExternalConfig {

private String developerName;

public String getDeveloperName() {
    return developerName;
}

public void setDeveloperName(String developerName) {
    this.developerName = developerName;
}   
}

最后我的 Springboot 主类看起来像这样

@EnableConfigurationProperties(ExternalConfig.class)
@SpringBootApplication
public class SpringBootMain implements CommandLineRunner {

@Autowired
ExternalConfig externalConfig;

@Bean
ResourceConfig resourceConfig() {
    return new ResourceConfig().registerClasses(ExternalConfig.class, Version1Api.class, Paypal.class);
}

public static void main(String[] args) {
    SpringApplication.run(SpringBootMain.class);
}

@Override
public void run(String... args) throws Exception {
    // TODO Auto-generated method stub
    System.out.println(externalConfig.getDeveloperName());

}  
}

每次我运行代码或调试它时,ExternalClass 及其变量始终为空。

我已经没有想法和方法来尝试以另一种方式做到这一点。我的 pom.xml 中是否缺少某些内容?

标签: javaspring-bootconfiguration

解决方案


这 2 项更改可能会有所帮助:

  1. 删除 application.properties 文件中 '=' 符号旁边的空格
  2. 从 @ConfigurationProperties 注释中删除单词 'prefix='。

更多信息:

一篇非常好的文章,其中包含有关提取应用程序属性的工作代码。

https://mkyong.com/spring-boot/spring-boot-configurationproperties-example/


推荐阅读