简体   繁体   中英

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.

eg user has input Name , the database has the value NameFinder() stored against this and the code needs to create an instance of 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.

I can't seem to find a guide that uses @Autowired classes so any help would be appreciated.

For autowiring to work you need the class which uses @Autowired to be a @Component (or a child like @Service...). 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

As for the reflective instantiation in the 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:

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. Try reading up on a BeanFactory or something similar. Usually reflection is to be avoided.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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