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

在SpringBoot项目中,非Controller层调用Service遇到NullPointerException。原因为非Controller层未使用@Component注解,导致Service无法自动装配。解决办法是在非Controller类上添加@Component注解,并使用@Autowired进行依赖注入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题描述:在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.youkuaiyun.com/y_yanghao/article/details/105083862
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值