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

相关推荐
APIshop32 分钟前
阿里巴巴中国站按图搜索1688商品(拍立淘)API 返回值说明
java·python·图搜索算法
前路不黑暗@35 分钟前
Java项目:Java脚手架项目的通用组件的封装(五)
java·开发语言·spring boot·学习·spring cloud·bootstrap·maven
哈库纳玛塔塔35 分钟前
dbVisitor 利用 queryForPairs 让键值查询一步到位
java·数据库·python
亓才孓1 小时前
[Stream]
java
J_liaty1 小时前
Spring事务详解
spring·事务
独自破碎E1 小时前
BISHI40数组取精
java·开发语言
❀͜͡傀儡师1 小时前
基于mybatis-plus进行加解密 Spring Boot Starter
spring boot·oracle·mybatis
丑八怪大丑1 小时前
Java面向对象(进阶)
java·开发语言
java1234_小锋1 小时前
Java高频面试题:Java中变量和常量有什么区别?
java·开发语言·面试
enjoy嚣士2 小时前
Java 之 实现C++库函数等价函数遇到的问题
java·开发语言·c++