[英]Spring Boot Configuration Not Working
I'm using Spring boot. 我正在使用Spring启动。
I have an application.yml
in src/main/resources
. 我在
src/main/resources
有一个application.yml
。 I then have a Configuration class that I am trying to get to load the application.yml
. 然后我有一个Configuration类,我试图加载
application.yml
。 However, when I try to use the configuration class in another bean, the values are null. 但是,当我尝试在另一个bean中使用配置类时,值为null。 See the
ApiHelper.java
as to where the values are null. 有关值为null的位置,请参阅
ApiHelper.java
。
I'm attempting to run the jar as so: 我试图像这样运行jar:
java -jar build/libs/app.jar
Am I doing something wrong? 难道我做错了什么? I've also tried using a properties file instead.
我也尝试过使用属性文件。 When I unzip the jar file the configuration files are in the root.
当我解压缩jar文件时,配置文件在根目录中。
src/main/resources/application.yml SRC /主/资源/ application.yml
spring:
profiles.active: default
---
spring:
profiles: default
api:
path: http://some-path
---
spring:
profiles: qa
api:
path: http://some-path2
src/main/java/AppConfig.java 的src /主/爪哇/ AppConfig.java
@Configuration
@EnableConfigurationProperties(ApiConfig.class)
public class AppConfig {
@Autowired
private ApiConfig apiConfig;
@ConfigurationProperties(value = "api", exceptionIfInvalid=true)
public static class ApiConfig {
private String path;
public ApiConfig() {
System.out.println("Am I getting called?"); // yes it is
}
public String getPath() {
return path;
}
}
@Bean
public ApiHelper getApiHelper() {
return new ApiHelper();
}
}
src/main/java/ApiHelper.java 的src /主/爪哇/ ApiHelper.java
public class ApiHelper {
@Autowired
private ApiConfig apiConfig;
@PostConstruct
private void init() {
System.out.println(apiConfig); // prints ApiConfig@168498d6
System.out.println(apiConfig.getPath()); // prints null
}
}
It turns out that you need a setter to make it work: 事实证明,你需要一个setter来使它工作:
@ConfigurationProperties(value = "api", exceptionIfInvalid=true)
public static class ApiConfig {
...
public void setPath(String path) {
this.path = path;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.