Spring 容器管理 反射生成的类

问题 & 背景

【问题描述】在开发中通过反射生成了类,反射类中注入的成员变量为null

【问题原因】因为反射生成的类没有交由springboot管理

【问题解决】反射生成类后,需要交由spring容器管理

代码

如果不交由spring容器管理,打断点发现testServicenull,执行testService.test()报空指针异常

public class TestCompute implements ICompute {
    @Autowired
    TestService testService;
    public void compute() {
        testService.test();
    }
}
Class<?> cls = null;
try {
    cls = Class.forName(computeRule.toString());
    // ICompute iCompute = (ICompute) cls.newInstance();
    ICompute iCompute = (ICompute) SpringUtil.getBean(cls);
    // 获取计算规则实例为空
    if (iCompute == null) {
        log.debug("====> class: {} is not fond", computeRule);
        throw new ServiceUserTagException("class " + computeRule + " is not found");
    }
    return iCompute;
} catch (Exception e) {
    log.error("class not found: {}, e: {}", computeRule, e);
    throw new ServiceUserTagException("class not found " + computeRule);
}
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class SpringUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if(SpringUtil.applicationContext == null) {
            SpringUtil.applicationContext = applicationContext;
        }
        log.info("ApplicationContext配置成功,applicationContext对象:"+SpringUtil.applicationContext);
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    public static <T> T getBean(String name,Class<T> clazz) {
        return getApplicationContext().getBean(name,clazz);
    }
}

参考

【1】springBoot @Autowired注入对象为空原因总结:https://blog.csdn.net/sunjinjuan/article/details/87255551

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容