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 !!! 加油 !!!

相关推荐
海鸥811 小时前
在K8S迁移节点kubelet数据存储目录
java·kubernetes·kubelet
jackson凌1 小时前
【Java学习笔记】递归
java·笔记·学习
鑫—萍1 小时前
C++——入门基础(2)
java·开发语言·jvm·数据结构·c++·算法
Excuse_lighttime2 小时前
UDP数据包和TCP数据包的区别;网络编程套接字;不同协议的回显服务器
java·tcp/ip·udp
心若微尘2 小时前
C++23/26 静态反射机制深度解析:编译时元编程的新纪元
java·开发语言·c++23
金斗潼关2 小时前
使用Nexus搭建远程maven仓库
java·maven·nexus
步行cgn2 小时前
Java Properties 遍历方法详解
java·开发语言·算法·面试·intellij-idea
heyCHEEMS2 小时前
[蓝桥杯 2023 国 Python B] 划分 Java
java·python·蓝桥杯
MyhEhud3 小时前
kotlin 过滤 filter 函数的作用和使用场景
android·java·服务器·前端·kotlin