欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot在啟動類main方法中調用service層方法報“空指針異?!暗慕鉀Q辦法

 更新時間:2024年06月27日 08:40:39   作者:芒果不是盲  
這篇文章主要介紹了SpringBoot在啟動類main方法中調用service層方法報“空指針異常“的解決辦法,大多數情況下,我們使用Springboot是創(chuàng)建一個maven項目,然后通過controller層的接口調用,但也有特殊情況,文章介紹的非常詳細,需要的朋友可以參考下

大多數情況下,我們使用Springboot是創(chuàng)建一個maven項目,然后通過controller層的接口調用。但也有特殊情況,比如將需要傳參的接口直接打包成可執(zhí)行jar包運行,這個時候,就需要在啟動類main方法中注入Bean,調用Service層方法使用。
按照常規(guī)service方法調用實現,報錯如下:

報錯原因:是service注入為空,service無法導入到非controller層中去

解決方法:注入bean

1、首先建立一個Spring工具類:SpringUtil

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負責配置、創(chuàng)建、管理Bean,是Spring容器最基本的接口;
BeanFactory的許多功能需要變成實現,而ApplicationContext中則可以通過配置的方式實現,即:
在構建容器的時候,ApplicationContext創(chuàng)建對象采用的策略是立即加載的方式,即只要一讀取完配置文件就立即創(chuàng)建配置文件中配置的對象。BeanFactory采用的是延遲加載的方式,什么時候根據id獲取對象了,什么時候才真正地創(chuàng)建對象。

2、在main方法中調用service,注意要啟動入口類 SpringApplication.run(TextCutApplication.class, args);

加載Spring配置文件時,如果Spring配置文件中所定義的類實現了ApplicationContextAware接口,那么在加載Spring配置文件時,會自動調用ApplicationContextAware接口中的setApplicationContext方法,獲得ApplicationContext對象。
ApplicationContext對象是由Spring注入的,前提必須在Spring配置文件中指定該類。

到此這篇關于SpringBoot在啟動類main方法中調用service層方法報“空指針異常“的解決辦法的文章就介紹到這了,更多相關SpringBoot service空指針異常內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論