使用class.forname但希望自动装配目标类的成员 [英] Using class.forname but want to autowire members of the target class

查看:103
本文介绍了使用class.forname但希望自动装配目标类的成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个要求,

我的框架以一种方式从配置文件中读取类名作为字符串,我想在里面使用方法那个类。

My framework is in a way that it reads the class name from the configuration file as a string and I would like to use methods inside that class.

明显的解决方案是使用反射,
我使用了反射并且能够调用我想要的方法,但问题是目标内部的变量班级不是自动装配的。我明白我不会让spring使用反射来自动化字段( Spring with class.forname())。

Obvious solution is to use reflection, I have used reflection and able to call methods I wanted, but the problem is the variables inside the target class are not autowired. I understand I am not letting spring to autowire the fields by using reflection (Spring with class.forname()).

我有没有办法自动装配类变量而不是创建新实例?还是我处于僵局?

Is there a way for me to autowire the class variables instead of creating new instance? Or Am I in a deadlock situation?

推荐答案

选项1 :如果您有权访问当前的Spring ApplicationContext ,您可以按如下方式执行此操作:

Option 1: If you have access to the current Spring ApplicationContext, you could do this as follows:

String className = <load class name from configuration>
Class<?> clazz = Class.forName(className);

ApplicationContext applicationContext = <obtain Spring ApplicationContext>
applicationContext.getBean(clazz);

这当然意味着您要加载其实例的类是Spring托管bean。这是一个具体的例子:

This of course means that the class whose instance you wish to load is a Spring managed bean. Here is a concrete example:

package org.example.beans;

@Component
class Foo { ... }

@Component
class SpringApplicationContext implements ApplicationContextAware {
  private static ApplicationContext CONTEXT;

  @Override
  public void setApplicationContext(final ApplicationContext context) throws BeansException
    CONTEXT = context;
  }

  public static <T> T getBean(String className) {
    return CONTEXT.getBean(Class.forName(className));
  }
}






选项2 :您可以手动创建所需类的实例,然后让Spring填充其依赖项。


Option 2: You could manually create an instance of the required class and then ask Spring to populate its dependencies.

这又需要访问的ApplicationContext 。例如:

T object = Class.forName(className).newInstance();

applicationContext..getAutowireCapableBeanFactory().autowireBean(object);

这篇关于使用class.forname但希望自动装配目标类的成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆