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

相关推荐
星秀日5 分钟前
Spring Boot + Sa-Token 实时聊天系统:用户注册流程源码深度剖析
java·人工智能·spring·状态模式
隐退山林16 分钟前
JavaEE进阶:MyBatis 操作数据库(入门)
数据库·java-ee·mybatis
YOU OU1 小时前
SpringBoot 配置文件
java·spring boot·后端
c++之路1 小时前
观察者模式(Observer Pattern)
java·网络·观察者模式
Dicky-_-zhang1 小时前
云原生存储与数据库选型实战:从传统数据库到云原生数据库的演进
java·jvm
凝小飞1 小时前
cucumber JAVA 一键部署指南
java·集成测试·模块测试
java修仙传1 小时前
Java 实习日记:断面状态筛选 Bug 修复与对比案例日期过滤优化
java·bug·实习
长谷深风1111 小时前
Java并发编程:线程安全与多线程实战指南【个人八股】
java·安全·线程·进程·juc·并发与并行·上下文切换(性能影响因素)
basketball6161 小时前
C++ 强制类型转换:从 C 风格到 C++ 四大金刚
java·c语言·c++
Dicky-_-zhang2 小时前
容器网络CNI实战:从零搭建网络插件
java·jvm