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

相关推荐
程序员张32 小时前
Maven编译和打包插件
java·spring boot·maven
ybq195133454313 小时前
Redis-主从复制-分布式系统
java·数据库·redis
weixin_472339463 小时前
高效处理大体积Excel文件的Java技术方案解析
java·开发语言·excel
小毛驴8504 小时前
Linux 后台启动java jar 程序 nohup java -jar
java·linux·jar
DKPT4 小时前
Java桥接模式实现方式与测试方法
java·笔记·学习·设计模式·桥接模式
好奇的菜鸟6 小时前
如何在IntelliJ IDEA中设置数据库连接全局共享
java·数据库·intellij-idea
DuelCode7 小时前
Windows VMWare Centos Docker部署Springboot 应用实现文件上传返回文件http链接
java·spring boot·mysql·nginx·docker·centos·mybatis
优创学社27 小时前
基于springboot的社区生鲜团购系统
java·spring boot·后端
幽络源小助理7 小时前
SpringBoot基于Mysql的商业辅助决策系统设计与实现
java·vue.js·spring boot·后端·mysql·spring
猴哥源码7 小时前
基于Java+springboot 的车险理赔信息管理系统
java·spring boot