springboot 反射调用ServiceImpl,报错:java.lang.NullPointerException,mapper为null

本文档介绍了一个SpringBoot应用在使用反射调用ServiceImpl时遇到Mapper为null的错误,以及如何通过创建SpringBootBeanUtil工具类来解决这个问题。在原始实现中,由于反射创建的对象无法初始化Dao接口,导致NullPointerException。解决方法是首先获取ApplicationContext,然后从容器中获取已经初始化的Bean来避免此问题。具体步骤包括创建SpringBootBeanUtil,实现ApplicationContextAware接口,以及调整反射调用的方法,通过ApplicationContext的getBean方法获取已实例化的Service对象。

springboot 使用反射调用ServiceImpl,报错:java.lang.NullPointerException

 是由于ServiceImpl的mapper为null导致的,以下为原实现代码:

           // 包名+类名
           Class classzz = Class.forName("com.XXX.XXX.service.impl.SenDataServiceImpl");

           // 获取构造器对象
           Constructor constructor = null;
           try {
               constructor = classzz.getConstructor();
           } catch (NoSuchMethodException e) {
               e.printStackTrace();
           }
           // 利用构造器对象创建一个对象
           Object o = constructor.newInstance();
           // 传递需要执行的方法 传递参数类型,如果没有可以不用填写
           Method method = classzz.getMethod("方法名称", long.class,String.class,String.class );
// invoke 方法,并传递参数,如果没有参数,可以不用填写
           Object obj =method.invoke(o,  5,
                  "param1",
                   "param2");

后查询方式,需要先ContextLoader.getCurrentWebApplicationContext(),但是还没有走到invoke,获取的ContextLoader.getCurrentWebApplicationContext()就为null。

最终解决实现的方式如下:

1.新建类 SpringBootBeanUtil

package com.smart.hyd.common.utils.reflect;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * SpringBoot 普通类获取Spring容器中的bean工具类
 */
@Component
public class SpringBootBeanUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (SpringBootBeanUtil.applicationContext == null) {
            SpringBootBeanUtil.applicationContext = applicationContext;
        }
        System.out.println("========ApplicationContext配置成功========");
//        System.out.println("========在普通类可以通过调用SpringBootBeanUtil.getApplicationContext()获取applicationContext对象========");
        System.out.println("========applicationContext="+ SpringBootBeanUtil.applicationContext +"========");
    }

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

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

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

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

}

2.调用SpringBootBeanUtil.getApplicationContext(),在invoke的时候,第一个参数applicationContext.getBean(ServiceImplType),具体实现参照下面代码。

try {
               //从ApplicationContext中取出已创建好的的对象
               //不可直接反射创建serviceimpi对象,因为反射创建出来的对象无法实例化dao接口
               ApplicationContext applicationContext = SpringBootBeanUtil.getApplicationContext();
               //反射创建serviceimpi实体对象,和实体类
               Class<?> ServiceImplType = Class.forName("com.XXX.XXX.service.impl.SenDataServiceImpl");
              // Class<?> entityType = Class.forName("com.XXX.XXX.service.impl.SenDataServiceImpl");
               //反射设置方法参数。
               Method method = ServiceImplType.getDeclaredMethod("方法名称",long.class,String.class,String.class );
               //在ApplicationContext中根据class取出已实例化的bean
               method.invoke(applicationContext.getBean(ServiceImplType), 5,
                           "param1",
                           "param2");

           } catch (ClassNotFoundException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
               e.printStackTrace();
               LOGGER.error("\n onMessage接收处理消息失败 - {}", "方法名称");
           }

这样就解决了反射调用ServiceImpl,mapper为null报错的问题。

参照解决方法的地址:

springboot中 利用java反射调用Service,注入Dao接口为null - 水狼一族 - 博客园

2025-03-10 19:11:03.893 ERROR [] [http-nio-17008-exec-172] com.genew.ems.common.aspect.GlobalExceptionHandler - Error while handle RuntimeException. java.lang.NullPointerException: null at com.hinmsbackground.business.service.impl.ne.NeDataBackupImpl.selsectNebackupInfo(NeDataBackupImpl.java:189) at com.hinmsbackground.business.controller.ne.NeDataBackupController.selsectNebackupInfo(NeDataBackupController.java:80) at com.hinmsbackground.business.controller.ne.NeDataBackupController$$FastClassBySpringCGLIB$$c20b2f78.invoke(<generated>) at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218) at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:771) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749) at org.springframework.aop.aspectj.AspectJAfterThrowingAdvice.invoke(AspectJAfterThrowingAdvice.java:62) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749) at org.springframework.aop.framework.adapter.AfterReturningAdviceInterceptor.invoke(AfterReturningAdviceInterceptor.java:55) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) 分析
03-11
@Service public class yibanServiceImpl extends ServiceImpl<yibanDao, yiban> implements yibanService { } public interface yibanService extends IService<yiban> { } package com.aaa.entity; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; //@TableName public class yiban { @TableId(type = IdType.AUTO) private Integer id; // @TableField("name") private String name; private Integer age; @Override public String toString() { return "yiban{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + '}'; } public yiban() { } public yiban(Integer id, String name, Integer age) { this.id = id; this.name = name; this.age = age; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } } package com.aaa.dao; import com.aaa.entity.yiban; import com.baomidou.mybatisplus.core.mapper.BaseMapper; public interface yibanDao extends BaseMapper<yiban> { } @Controller public class yibanController { @Resource yibanService yibanService; @ResponseBody @RequestMapping("/pageYb") public PageInfo<yiban> ybList(Integer currentPage , Integer PageSize){ PageHelper.startPage(currentPage,PageSize); List<yiban> list = yibanService.list(); PageInfo<yiban> yibanPageInfo = new PageInfo<>(list); return yibanPageInfo; } } 帮我筛查 为什么会空指针异常
09-10
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值