先贴上错误代码:
@Component
@ConfigurationProperties(prefix = "toss")
public class TossConfig {
/**文件上传路径*/
private static String profile;
public static String getProfile() {
return profile;
}
public static void setProfile(String profile) {
TossConfig.profile = profile;
}
public static String getDownloadPath(){
return profile + "download/";
}
}
项目运行后发现 profile取值是 null;
这是因为@ConfigurationProperties只会调用 非静态的set方法,所以稍做改动,set方法都换成非静态的,贴下正确的代码:
@Component
@ConfigurationProperties(prefix = "toss")
public class TossConfig {
/**文件上传路径*/
private static String profile;
public static String getProfile() {
return profile;
}
public void setProfile(String profile) {
TossConfig.profile = profile;
}
public static String getDownloadPath(){
return profile + "download/";
}
}
本文探讨了在Spring Boot项目中使用@ConfigurationProperties注解时遇到的问题,即配置属性无法正确注入静态字段。通过示例代码展示了错误的静态set方法导致的profile值为null的问题,并给出了将set方法改为非静态的解决方案。
1万+

被折叠的 条评论
为什么被折叠?



