springboot中非controller层调用service报java.lang.NullPointerException

问题描述:在springboot项目中,非controller层调用service服务时,报java.lang.NullPointerException这个错误,即service无法导入到非controller层中去。

原因分析:简单描述一下,这个就是springboot自动装配的缺陷之一了,springboot中基本上所有的注解都继承了component这个注解(需要看源码,这里就不详细描述了),有了component就自动装配了。而你的非controller没有继承component这个注解,所以无法导入,一直未null。

解决方案:注释写的详细直接贴代码了

package com.jwdntjfx.util;

import com.jwdntjfx.domain.People;
import com.jwdntjfx.service.InsertExcelToOracleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @Component 注解别忘了
 */
@Component
public class TestUtil {

    /**
     * 你需要调用的service
     */
    @Autowired
    private InsertExcelToOracleService insertExcelToOracleService;
    /**
     * 这个类  注意要public,不要private
     */
    @Autowired
    public static TestUtil testUtil;
    
    /**
     * 重新构造一个方法
     * @PostContruct 这个注解就是在springboot启动前就加载
     */
    @PostConstruct
    public void init(){
        testUtil=this;
        testUtil.insertExcelToOracleService=this.insertExcelToOracleService;
    }
    
    /**
     * 这是我测试的一个方法
     * 向数据库中插入一条信息
     * @return
     */
    public int test(){
        People people=new People();
        people.setSfzh("test");
        people.setXm("test");
        people.setSsz("test");
        people.setType("test");
        //这里需要注意service前面别漏了testUtil
        int a= testUtil.insertExcelToOracleService.insertExcelToOracle(people);
        return a;
    }
}

直接建立一个测试类(在controller中建立)测试一下,new一下TestUtil,调用里面的test()方法。Ok问题解决了。

本文链接:https://blog.csdn.net/y_yanghao/article/details/105083862

版权声明:本文为y_yanghao原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。