简体   繁体   English

如何使用 Java 反射创建@Autowired class 的实例

[英]How to use Java reflection to create an instance of an @Autowired class

I have a postgres database which stores (as a String) the relevant class to use dependent on the information coming in from the user.我有一个 postgres 数据库,它存储(作为字符串)相关的 class 以根据来自用户的信息使用。

eg user has input Name , the database has the value NameFinder() stored against this and the code needs to create an instance of NameFinder().例如,用户输入了Name ,数据库中存储了 NameFinder() 值,代码需要创建 NameFinder() 的实例。

I was wondering if there was a way of using reflection to instantiate this class as an @Autowired component, and then call the relevant function.我想知道是否有一种方法可以使用反射将此 class 实例化为@Autowired 组件,然后调用相关的 function。

I can't seem to find a guide that uses @Autowired classes so any help would be appreciated.我似乎找不到使用 @Autowired 类的指南,因此将不胜感激。

For autowiring to work you need the class which uses @Autowired to be a @Component (or a child like @Service...).要使自动装配工作,您需要 class 它使用 @Autowired 作为 @Component(或像 @Service 的孩子......)。 https://www.baeldung.com/spring-autowire https://www.baeldung.com/spring-autowire

For Spring to know what to inject, you need to define a @Bean in your Configuration https://www.baeldung.com/spring-bean要让 Spring 知道要注入什么,您需要在配置中定义 @Bean https://www.baeldung.com/spring-bean

As for the reflective instantiation in the bean:至于bean中的反射实例化:

@Bean
public Name getName(Database db) {
    String nameFqn = db.getConfigTable().getNameFQN();
    return (Name) Class.forName(nameFqn).getConstructor().newInstance();
}

Note this uses a no-arg public constructor.请注意,这使用无参数公共构造函数。 FQN means fully-qualified name, ie com.some.pkg.NameFinder assuming: FQN 表示完全限定名称,即com.some.pkg.NameFinder假设:

package com.some.pkg;

class NameFinder implements Name {
    public NameFinder(){}
}

I feel like a Spring Bean should be configurable also directly from a FQN without using reflection but I don't know how.我觉得 Spring Bean 也应该可以直接从 FQN 配置而不使用反射,但我不知道如何配置。 Try reading up on a BeanFactory or something similar.尝试阅读 BeanFactory 或类似的东西。 Usually reflection is to be avoided.通常要避免反射。

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

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