问题复盘|Spring Boot 项目启动时避免空指针异常的解决方案

文章目录

    • 问题描述
    • 解决方案
      • [1. 使用 `@Autowired` 注入](#1. 使用 @Autowired 注入)
      • [2. 延迟初始化](#2. 延迟初始化)
      • [3. 使用 `@PostConstruct` 注解](#3. 使用 @PostConstruct 注解)
      • [4. 确保 `ApplicationContextHolder` 初始化正确](#4. 确保 ApplicationContextHolder 初始化正确)
    • 结论

Hello大家好,我是阿月,坚持学习,老年痴呆追不上我。
在Spring Boot项目中,空指针异常(NullPointerException, NPE)是常见的问题之一,尤其是在Spring容器尚未完全初始化时试图获取Bean对象。今天我们将探讨在Spring Boot项目启动时如何避免此类异常,并提供几种有效的解决方案。

问题描述

在Spring Boot项目启动时,以下代码导致了空指针异常:

java 复制代码
DepartmentMapper departmentMapper = ApplicationContextHolder.getApplicationContext().getBean(DepartmentMapper.class);

该代码片段位于一个标注为@Component的类中:

java 复制代码
@Component
public class ClusterConfig {

    public static List<ClusterItemConfig> clusterItemConfigList;

    DepartmentMapper departmentMapper = ApplicationContextHolder.getApplicationContext().getBean(DepartmentMapper.class);

    @Value("${clusterConfigList:[]}")
    private void setValue(String clusterConfigList) {
        List<ClusterItemConfig> result = new Gson().fromJson(clusterConfigList, new TypeToken<ArrayList<ClusterItemConfig>>() {
        }.getType());
        result.forEach(clusterBaseConfig ->
                clusterBaseConfig.setDepartmentCodeList(
                        departmentMapper.getCodeListByName(clusterBaseConfig.getDepartmentNameList())));
        ClusterConfig.clusterItemConfigList = result;
    }
}

问题出在Spring容器尚未完全初始化时,ApplicationContextHolder.getApplicationContext()返回null,导致departmentMapper为空。

解决方案

1. 使用 @Autowired 注入

使用@Autowired注解将DepartmentMapper注入到ClusterConfig类中,让Spring自动管理DepartmentMapper的初始化和注入。

java 复制代码
@Component
public class ClusterConfig {

    public static List<ClusterItemConfig> clusterItemConfigList;

    @Autowired
    private DepartmentMapper departmentMapper;

    @Value("${clusterConfigList:[]}")
    private void setValue(String clusterConfigList) {
        List<ClusterItemConfig> result = new Gson().fromJson(clusterConfigList, new TypeToken<ArrayList<ClusterItemConfig>>() {
        }.getType());
        result.forEach(clusterBaseConfig ->
                clusterBaseConfig.setDepartmentCodeList(
                        departmentMapper.getCodeListByName(clusterBaseConfig.getDepartmentNameList())));
        ClusterConfig.clusterItemConfigList = result;
    }
}

2. 延迟初始化

在方法内部延迟获取Bean,只在需要时通过ApplicationContextHolder获取DepartmentMapper

java 复制代码
@Component
public class ClusterConfig {

    public static List<ClusterItemConfig> clusterItemConfigList;

    @Value("${clusterConfigList:[]}")
    private void setValue(String clusterConfigList) {
        DepartmentMapper departmentMapper = ApplicationContextHolder.getApplicationContext().getBean(DepartmentMapper.class);
        List<ClusterItemConfig> result = new Gson().fromJson(clusterConfigList, new TypeToken<ArrayList<ClusterItemConfig>>() {
        }.getType());
        result.forEach(clusterBaseConfig ->
                clusterBaseConfig.setDepartmentCodeList(
                        departmentMapper.getCodeListByName(clusterBaseConfig.getDepartmentNameList())));
        ClusterConfig.clusterItemConfigList = result;
    }
}

3. 使用 @PostConstruct 注解

使用@PostConstruct注解确保在Spring容器初始化完成后执行特定的初始化逻辑。

java 复制代码
@Component
public class ClusterConfig {

    public static List<ClusterItemConfig> clusterItemConfigList;

    @Autowired
    private DepartmentMapper departmentMapper;

    @Value("${clusterConfigList:[]}")
    private String clusterConfigList;

    @PostConstruct
    private void init() {
        List<ClusterItemConfig> result = new Gson().fromJson(clusterConfigList, new TypeToken<ArrayList<ClusterItemConfig>>() {
        }.getType());
        result.forEach(clusterBaseConfig ->
                clusterBaseConfig.setDepartmentCodeList(
                        departmentMapper.getCodeListByName(clusterBaseConfig.getDepartmentNameList())));
        ClusterConfig.clusterItemConfigList = result;
    }
}

4. 确保 ApplicationContextHolder 初始化正确

确保ApplicationContextHolder能正确获取ApplicationContext,并在所有Bean初始化后能够正常工作。

java 复制代码
@Component
public class ApplicationContextHolder implements ApplicationContextAware {

    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return context;
    }
}

结论

通过以上方法之一,可以确保在Spring容器完全初始化后,正确地获取DepartmentMapper Bean,从而避免空指针异常。在实际项目中,根据具体情况选择合适的方案,确保代码的稳定性和可维护性。

如果还有任何疑问或建议,欢迎在评论区留言讨论。

相关推荐
Ylucius32 分钟前
动态语言? 静态语言? ------区别何在?java,js,c,c++,python分给是静态or动态语言?
java·c语言·javascript·c++·python·学习
凡人的AI工具箱43 分钟前
AI教你学Python 第11天 : 局部变量与全局变量
开发语言·人工智能·后端·python
是店小二呀1 小时前
【C++】C++ STL探索:Priority Queue与仿函数的深入解析
开发语言·c++·后端
七夜zippoe1 小时前
分布式系统实战经验
java·分布式
canonical_entropy1 小时前
金蝶云苍穹的Extension与Nop平台的Delta的区别
后端·低代码·架构
是梦终空1 小时前
JAVA毕业设计176—基于Java+Springboot+vue3的交通旅游订票管理系统(源代码+数据库)
java·spring boot·vue·毕业设计·课程设计·源代码·交通订票
落落落sss1 小时前
sharding-jdbc分库分表
android·java·开发语言·数据库·servlet·oracle
码爸1 小时前
flink doris批量sink
java·前端·flink
我叫啥都行2 小时前
计算机基础知识复习9.7
运维·服务器·网络·笔记·后端
工业互联网专业2 小时前
毕业设计选题:基于springboot+vue+uniapp的驾校报名小程序
vue.js·spring boot·小程序·uni-app·毕业设计·源码·课程设计