所以我几乎遵循了所有的教程/示例和堆栈溢出问题,但我似乎仍然无法让我的应用程序属性文件能够在我创建的 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 及其变量始终为 null。
我正在用完尝试另一种方式的想法和方法。我的绒球.xml中缺少什么吗?
以下 2 项更改可能会有所帮助:
- 删除应用程序属性文件中"="符号旁边的空格
- 从@ConfigurationProperties注释中删除单词"prefix="。
更多信息:
一篇非常好的文章,其中包含有关提取应用程序属性的工作代码。
https://mkyong.com/spring-boot/spring-boot-configurationproperties-example/
我认为你应该以不同的方式定义豆子
@Configuration
@ConfigurationProperties(prefix="spring.boot.config")
public class ExternalConfig {