我正在尝试使用组件来加载我的配置 yml 文件。
但是,它会引发空指针异常,并且 System.out 显示应用程序为“null”。
但是,当使用相同的模式来编写 @RestController 时,一切正常。为什么@component看不到我的配置?
@Component
@ConfigurationProperties(prefix = "myconf")
public class AppConfigJSON {
private String application;
private final String applicationConfigJSON;
Logger logger = LoggerFactory.getLogger(this.getClass());
private final ReadContext acRcJson;
public AppConfigJSON(){
String json = "";
try {
System.out.println("Application: " + this.application);
json = IOUtils.toString(this.getClass().getResourceAsStream("/myconfs/"+this.application+".json"));
} catch (IOException e) {
logger.error("Error reading JSON or app YML {}", e.getStackTrace());
}
this.applicationConfigJSON = json;
this.acRcJson = JsonPath.parse(this.getApplicationConfigJSON());
}
// These functions below set by configuration
public String getApplication()
{
return application;
}
public void setApplication(String application)
{
this.application = application;
}
}
最佳答案
在你的构造函数中,application 变量还没有被初始化,换句话说,Spring 首先需要一个实例,这样它才能应用它的魔力。您需要将构造函数逻辑移至用 @PostContruct
注解的方法,以便使用此时的属性值设置应用程序变量。
关于Java Spring Boot 配置和组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42613887/