先上结论 springboot中,yml配置文件中设置lazy-init后,有时会导致@ConfigurationProperties注解标注的bean对象没有读取到yml中的值。
问题复现
项目中需要实现在不同环境下切换文件上传目录,u
application.yml配置:
spring:
#省略
main:
lazy-initialization: ture
#file用于读取文件信息
file:
download: G:\Code\qz-water-monitor\file\download\
template: G:\Code\qz-water-monitor\file\template\
upload: G:\Code\qz-water-monitor\file\upload\
java代码(设置了静态字段,以便于使用)
@Component
@ConfigurationProperties(prefix = "lm")
public class FileProperties {
private String template;
private String upload;
// 注意这里设置了静态字段
private static String download;
public String getTemplate() {
return template;
}
public void setTemplate(String template) {
this.template = template;
}
public String getUpload() {
return upload;
}
public void setUpload(String upload) {
this.upload = upload;
}
public static String getDownload() {
return FileProperties.download;
}
// 静态字段set方法不能为static修饰
public void setDownload(String download) {
FileProperties.download = download;
}
}
java代码:在其他类中使用,FileProperties.getDownload()调用,会出现值为null的情况。
public class FileUtils {
public static String getLocalPathDownload() {
return FileProperties.getDownload();//值为null
}
}
原因
@ConfigurationProperties注解是通过spring自动装配实现的,lazy-init设置为true,Spring就不会在项目启动时就加载Bean,导致被@ConfigurationProperties注解的类没有完成装配。