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;
            ...
    }
}

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值