Reputation: 3
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
Upvotes: 0
Views: 734
Reputation: 19926
Short Answer
That's not possible. Spring needs to know what Beans there are for injecting them.
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. 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);
}
}
Upvotes: 1
Reputation: 810
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/
Upvotes: 0
Reputation: 3805
Not sure it's a good idea, but you can inject a class like mentionned here : Injecting beans into a class outside the Spring managed context
Upvotes: 0