【springboot】反射 导致的注入bean为null

问题描述

原因分析

由于灵活性,在调用校验逻辑时用了反射,如下

// arr数组为配置的不同的校验方法,arr[0]是类名,arr[1]是方法名,PATH是类的全路径
Class<?> cls = Class.forName(PATH + arr[0]);
Method method = cls.getMethod(arr[1], String.class);
boolean flag = (boolean) method.invoke(cls.newInstance(), requestDto.getCustId());

这个反射的问题在于,创建的类并不在spring容器中进行管理,相当于A a = new A(),故注入的Bean为空。

解决方法

修改反射的用法,如下

Class<?> cls = SpringContextUtil.getBean(arr[0]).getClass();
Method method = cls.getMethod(arr[1], String.class);
boolean flag = (boolean) method.invoke(SpringContextUtil.getBean(arr[0]), requestDto.getCustId());

其中的StringContextUtil 如下

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;

/**
 * @author xxx
 * @date 2022-06-27 11:06
 */
@Configuration
public class SpringContextUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

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


    public static Object getBean(String name) throws BeansException {
        return applicationContext.getBean(name);
    }
}

参考文章

经验分享 程序员 微信小程序 职场和发展