美文网首页
Java通过反射加载的类中的变量无法注入的解决办法

Java通过反射加载的类中的变量无法注入的解决办法

作者: undefined可以吗 | 来源:发表于2017-11-12 20:11 被阅读0次

在Java中定义一个类,类中注入了一个service,代码如下:

@Component
public class AffairIdHandler implements PropertyHandler {

    @Autowired
    private AffairService affairService;

    @Override
    public JSONObject handle(JSONObject auditData, String handleKey) {
        Long affairId = auditData.getLong(handleKey);
        JSONObject affair = new JSONObject();
        //......
        return affair;
    } 
}

但是由于AffairIdHandler需要通过反射动态地加载,使用它的类不是通过注入的方式获取实例的,导致AffairService无法由spring自动注入,因为AffairIdHandler已经脱离spring的管理,所以affairService变量为null,具体的解决办法如下:

@Service
public class OperationService {

    @Autowired
    private ApplicationContext context;

    public List<JSONObject> handleProperties(KeyMapper.Operation operation, JSONObject auditData) {
        List<JSONObject> form = new ArrayList<>();
        Map<String, KeyMapper.Operation.Property> properties = operation.getProperties();
        for (Map.Entry<String, KeyMapper.Operation.Property> entry : properties.entrySet()) {
            //......
            if (handlerUrl == null) {
                component.put("value", auditData.get(key));
            } else {
                try {
                    Class<?> handler =  Class.forName(handlerUrl);
                    PropertyHandler propertyHandler = (PropertyHandler)context.getAutowireCapableBeanFactory()
                                        .createBean(handler, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }

            }
            form.add(component);
        }
        return form;
    }

}

即使用ApplicationContext获取AutowireCapableBeanFactory示例,并通过AutowireCapableBeanFactory的实例的createBean()方法来创建bean,那么AffairIdHandler类中使用@Autowired注入的变量就可以自动注入。

相关文章

  • Java通过反射加载的类中的变量无法注入的解决办法

    在Java中定义一个类,类中注入了一个service,代码如下: 但是由于AffairIdHandler需要通过反...

  • Java基础之反射

    Java-Reflect Class类的使用 方法的反射 成员变量的反射 构造函数的反射 Java类加载机制 一、...

  • Spring 容器管理 反射生成的类

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

  • java基础3

    1、说说对Class类的理解 2、说说Class/Java动态加载类 3、通过反射获取类的方法、变量等 4、方法的...

  • 反射Class

    class类的使用 方法的反射 成员变量的反射 构造函数的反射 Java类加载机制 反射帮我们做一些程序运行时刻的...

  • 2018-08-30

    Java反射 类的反射方法: new 创建对象 是静态加载类,在编译时刻就需要加载所有的可能使用到的类。 通过动态...

  • Java学习笔记 27 - 类的加载器、反射

    本文内容介绍1、类加载器2、反射构造方法3、反射成员变量4、反射成员方法5、反射配置文件运行类中的方法 01类加载...

  • 在Java的反射中,Class.forName和ClassLoa

    在Java反射中Class.forName()加载类和使用ClassLoader加载类的区别。解释 在java中C...

  • java 反射全面总结

    反射总结慕课网 反射的视频 什么是反射 反射是能够让java代码访问一个已经加载的类的字段,变量,方法和构造器等信...

  • Java反射

    什么是反射 一个类有多个组成部分,如成员变量,方法,构造方法等。反射就是加载类,并解剖出类的各个组成部分Java反...

网友评论

      本文标题:Java通过反射加载的类中的变量无法注入的解决办法

      本文链接:https://www.haomeiwen.com/subject/wdeomxtx.html