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

相关推荐
犀利豆13 分钟前
AI in Harness(二)
java·人工智能·后端
沉静的小伙2 小时前
在微服务中使用领域事件
java·运维·微服务
程序员在囧途2 小时前
likeadmin-api API 算力超市怎么做供应商切换?统一鉴权、task_id 和 callback_url 才能稳交付
java·服务器·数据库·开放api·likeadmin-api·api算力超市
醇氧2 小时前
Spring 容器 Map 注入机制详解
java·后端·spring
栈溢出了3 小时前
Java Lambda 表达式笔记
java·开发语言·intellij-idea
会周易的程序员3 小时前
使用 pybind11 封装 C++ 日志库 microLog 为 Python 模块
java·c++·python·物联网·架构·日志·aiot
zhixingheyi_tian3 小时前
一份GC日志的解读
java·开发语言
ywl4708120873 小时前
ArrayList和LinkedList内部的实现原理和区别
java·java基础
沉静的小伙3 小时前
Spring事务
java·数据库·spring
apihz3 小时前
随机驾考题目(C 照科一 / 科四 2000+ 题)免费API调用教程
android·java·c语言·开发语言·网络协议·tcp/ip