简体   繁体   English

如何在运行时使用方法自动连接类

[英]How to Autowire a class at runtime in a method

Is it possible to Autowire fields in a dynamic class? 是否可以自动连接动态类中的字段? I am getting a class name from the database and I want to autowire this class 我从数据库中获取一个班级名称,我想自动连接该班级

Short Answer 简短答案

That's not possible. 那不可能 Spring needs to know what Beans there are for injecting them. Spring需要知道有哪些Bean可以注入它们。

Long Answer 长答案

You could @Autowire every possible bean into a class and then cache them in a Map, where the Class represents the key, and the Object the value. 您可以@Autowire所有可能的bean放入一个类,然后将它们缓存在Map中,其中Class代表键,Object则值。 See below simplified example: 请参见下面的简化示例:

public class MyClass{
     private final Map<Class<?>, Object> cache = new HashMap<>();

     @Autowired
     public MyClass(Service1 s1, Service2 s2){
         // registering the beans
         cache.put(Service1.class, s1);
         cache.put(Service2.class, s2);
     }

     public <T> T getService(String className) throws ClassNotFoundException{
         // getting the bean
         Class<?> clazz = Class.forName(className);
         return (T) cache.get(clazz);
     }
}

不确定这是一个好主意,但是您可以注入这里提到的类: 将bean注入Spring托管上下文之外的类中

You can try this: 您可以尝试以下方法:

import javax.annotation.PostConstruct;

@Component
public class ApplicationContextAccessor {

private static ApplicationContextAccessor instance;

@Autowired
private ApplicationContext applicationContext;

public static  T getBean(Class clazz) {
    return instance.applicationContext.getBean(clazz);
}

@PostConstruct
private void registerInstance() {
    instance = this;
}

} }

Read this post : https://www.helicaltech.com/uses-of-springs-applicationcontext-while-using-reflection/ 阅读这篇文章: https : //www.helicaltech.com/uses-of-springs-applicationcontext-while-using-reflection/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM