解决:springboot在启动类main方法中调用service层方法报“空指针异常“

大多数情况下,我们使用Springboot是创建一个maven项目,然后通过controller层的接口调用。但也有特殊情况,比如将需要传参的接口直接打包成可执行jar包运行,这个时候,就需要在启动类main方法中注入Bean,调用Service层方法使用。

按照常规service方法调用实现,报错如下:

报错原因:是service注入为空,service无法导入到非controller层中去

解决方法:注入bean

1、首先建立一个Spring工具类:SpringUtil

java 复制代码
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class SpringUtil implements ApplicationContextAware {
    private static ApplicationContext applicationContext = null;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if(SpringUtil.applicationContext == null){
            SpringUtil.applicationContext  = applicationContext;
        }
    }


    //获取applicationContext
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    //通过name获取 Bean.
    public static Object getBean(String name){
        return getApplicationContext().getBean(name);
    }

    //通过class获取Bean.
    public static <T> T getBean(Class<T> clazz){
        return getApplicationContext().getBean(clazz);
    }

    //通过name,以及Clazz返回指定的Bean
    public static <T> T getBean(String name,Class<T> clazz){
        return getApplicationContext().getBean(name, clazz);
    }
}

ApplicationContextAware :

当一个类实现ApplicationContextAware接口后,这个类就可以方便获得ApplicationContext中所有的bean。简言之,就是这个类可以直接获取spring配置文件中所有有引用到的bean对象。

ApplicationContext:

ApplicationContext是由BeanFactory派生而来的,BeanFactory负责配置、创建、管理Bean,是Spring容器最基本的接口;

BeanFactory的许多功能需要变成实现,而ApplicationContext中则可以通过配置的方式实现,即:

在构建容器的时候,ApplicationContext创建对象采用的策略是立即加载的方式,即只要一读取完配置文件就立即创建配置文件中配置的对象。BeanFactory采用的是延迟加载的方式,什么时候根据id获取对象了,什么时候才真正地创建对象。

2、在main方法中调用service,注意要启动入口类 SpringApplication.run(TextCutApplication.class, args);

加载Spring配置文件时,如果Spring配置文件中所定义的类实现了ApplicationContextAware接口,那么在加载Spring配置文件时,会自动调用ApplicationContextAware接口中的setApplicationContext 方法,获得ApplicationContext对象。

ApplicationContext对象是由Spring注入的,前提必须在Spring配置文件中指定该类。

相关推荐
好好研究2 小时前
总结SSM设置欢迎页的方式
xml·java·后端·mvc
小马爱打代码3 小时前
Spring Boot:第三方 API 调用的企业级容错设计
java·spring boot·后端
csdn2015_4 小时前
springboot task
java·spring boot·后端
czlczl200209254 小时前
Spring Boot :如何高性能地在 Filter 中获取响应体(Response Body)
java·spring boot·后端
码界奇点5 小时前
基于Spring Boot和Vue3的无头内容管理系统设计与实现
java·spring boot·后端·vue·毕业设计·源代码管理
To Be Clean Coder6 小时前
【Spring源码】createBean如何寻找构造器(二)——单参数构造器的场景
java·后端·spring
你才是臭弟弟6 小时前
SpringBoot 集成MinIo(根据上传文件.后缀自动归类)
java·spring boot·后端
C澒6 小时前
面单打印服务的监控检查事项
前端·后端·安全·运维开发·交通物流
鸣潮强于原神6 小时前
TSMC chip_boundary宽度规则解析
后端
Code blocks7 小时前
kingbase数据库集成Postgis扩展
数据库·后端