问题复盘|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,从而避免空指针异常。在实际项目中,根据具体情况选择合适的方案,确保代码的稳定性和可维护性。

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

相关推荐
一 乐35 分钟前
心理咨询|学生心理咨询评估系统|基于Springboot的学生心理咨询评估系统设计与实现(源码+数据库+文档)
java·数据库·spring boot·后端·论文·毕设·学生心理咨询评估系统
anthem371 小时前
第三阶段_大模型应用开发-Day 4: RAG检索增强生成技术
后端
Java技术小馆1 小时前
Gemini Storybook AI驱动的交互式故事创作
java·程序员·架构
用户4099322502121 小时前
如何让Celery任务像VIP客户一样享受优先待遇?
后端·github·trae
dylan_QAQ1 小时前
【附录】Spring 环境配置 基础及应用
后端·spring
码神本神2 小时前
(附源码)基于Spring Boot的4S店信息管理系统 的设计与实现
java·spring boot·后端
天天摸鱼的java工程师2 小时前
SpringBoot + Seata + MySQL + RabbitMQ:金融系统分布式交易对账与资金清算实战
java·后端·面试
anthem372 小时前
第三阶段_大模型应用开发-Day 3: 大模型推理优化与部署
后端
dylan_QAQ2 小时前
【附录】Spring 资源访问 基础及应用
后端·spring
别来无恙1492 小时前
Spring Boot文件上传功能实现详解
java·spring boot·文件上传