2023-08-23 Spring加载问题

起因

写了一个缓存,这个缓存不会变动,我在final中加载,发现报错了。

java 复制代码
 private final Map<Integer,String> companyMap;

    {
        departmentMap =  departmentService.list().stream()
                .collect(Collectors.toMap(DepartmentEntity::getId, DepartmentEntity::getName));

        companyMap = companyService.list().stream()
            .collect(Collectors.toMap(Company::getId, Company::getName));
    } 
复制代码
代码报错 org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'jobPositionController': Unsatisfied dependency expressed through field 'jobPositionService'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jobPositionService' defined in file [E:\Team Garde\team-garden-backend\target\classes\io\renren\modules\position\service\impl\JobPositionServiceImpl.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [io.renren.modules.position.service.impl.JobPositionServiceImpl]: Constructor threw exception; nested exception is java.lang.NullPointerException

解决

作为一个对Spring熟知的男人,我一眼就看出了问题所在,原因是在 JobPositionServiceImpl 的构造函数中使用了 departmentService 或 companyService,而这两个依赖的 bean 没有正确地注入,导致调用它们的方法时出现了空指针异常。

OK,我秒解决了这个问题

java 复制代码
    private final Map<Integer,String> departmentMap;

    private final Map<Integer,String> companyMap;

    @Autowired
    public JobPositionServiceImpl(DepartmentService departmentService, CompanyService companyService) {
        this.departmentService = departmentService;
        this.companyService = companyService;
        this.departmentMap = initDepartmentMap();
        this.companyMap = initCompanyMap();
    }

    private Map<Integer, String> initDepartmentMap() {
        return departmentService.list().stream()
                .collect(Collectors.toMap(DepartmentEntity::getId, DepartmentEntity::getName));
    }

    private Map<Integer, String> initCompanyMap() {
        return companyService.list().stream()
                .collect(Collectors.toMap(Company::getId, Company::getName));
    }

问题解决,继续写业务代码

后续

在开发中可能遇到各种问题,但是你只要拥有对源码的理解,毛毛雨啦~~~

哈哈哈,皮一下 !

我们日常开发,一定要停下一点时间,看看Spring源码,你会发现你的职业生涯就像开挂一样! 什么 Mybatis,什么 Lucene,只要怼着官方手册,就是一梭子的事情。

向Spring的开发人员致敬!!!

最后:
TEAM GARDEN !!! 加油 !!!

相关推荐
代码写到35岁3 分钟前
【Java 单体架构改造 微服务 网关遇坑之 跨域配置】
java·微服务·架构
qq_12498707538 分钟前
基于Java的心理测试系统的设计与实现(源码+论文+部署+安装)
java·开发语言·vue.js·spring boot·计算机毕设·计算机毕业设计
拽着尾巴的鱼儿9 分钟前
Spring定时任务 Scheduled使用
java·后端·spring
沉默-_-22 分钟前
力扣hot100双指针专题解析2(C++)
java·c++·算法·蓝桥杯·双指针
Jaxson Lin24 分钟前
Java编程进阶:智能仿真无人机项目1.0
java·开发语言
sheji341632 分钟前
【开题答辩全过程】以 实验室设备管理系统为例,包含答辩的问题和答案
java
江君是实在人37 分钟前
java 面试题 redis 处理大key问题
java·开发语言·redis
Filotimo_41 分钟前
Spring MVC 注解家族
java
禁默1 小时前
Portainer:让 Docker 管理变简单,用cpolar突破局域网后协作更轻松
java·docker·容器·cpolar
麦兜*1 小时前
SpringBoot 3.x新特性全面解析:从Java 17支持到GraalVM原生镜像
java·spring boot·后端