Reputation: 73
I have a postgres database which stores (as a String) the relevant class to use dependent on the information coming in from the user.
e.g. 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.
Upvotes: 1
Views: 2392
Reputation: 2142
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, i.e. 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.
Upvotes: 1