Springboot项目中使用@Autowired自动装配的对象,使用时报null异常
项目中需要从application.yml文件中读取一个配置属性值,类在项目中的关系如下图:
配置类如下:
@Configuration
public class ExcelConfig {
private String basePath;
public String getBasePath() {
return basePath;
}
@Value("${excel.basePath}")
public void setBasePath(String basePath) {
this.basePath = basePath;
}
}
打断点debug启动时,可以看到确实为属性赋值了。
在如下类中使用@Autowired自动装配,然后调用获取属性的get方法,抛出了空指针异常java.lang.NullPointerException
@Service
public class ExportDataToExcelJob extends IJobHandler {
@Autowired
private ExcelConfig excelConfig;
@Override
public ReturnT<String> execute(String s) throws Exception {
try {
String yesterday = DateUtils.getYesterday();
String directory = excelConfig.getBasePath();
...
}
}
具体的原因还没有找到,尝试了以下两种解决办法,做下记录以后再遇到可以借鉴:
1)使用@PostConstruct注解,该方法会在服务器加载Servlet的时候运行,并且只会被服务器调用一次
@Service
public class ExportDataToExcelJob extends IJobHandler {
@Autowired
private ExcelConfig excelConfig;
public static ExportDataToExcelJob exportDataToExcelJob;
@PostConstruct
public void init(){
exportDataToExcelJob = this;
exportDataToExcelJob.excelConfig = this.excelConfig;
}
@Override
public ReturnT<String> execute(String s) throws Exception {
try {
String yesterday = DateUtils.getYesterday();
String directory = exportDataToExcelJob.excelConfig.getBasePath();
...
}
}
2)修改配置类,将属性设置为静态变量
@Configuration
public class ExcelConfig {
public static String basePath;
@Value("${excel.basePath}")
public void setBasePath(String basePath) {
ExcelConfig.basePath = basePath;
}
}
直接使用ExcelConfig.basePath调用改属性
@Service
public class ExportDataToExcelJob extends IJobHandler {
public static ExportDataToExcelJob exportDataToExcelJob;
@PostConstruct
public void init(){
exportDataToExcelJob = this;
exportDataToExcelJob.excelConfig = this.excelConfig;
}
@Override
public ReturnT<String> execute(String s) throws Exception {
try {
String yesterday = DateUtils.getYesterday();
String directory = ExcelConfig.basePath;
...
}
}