With Spring 4.x I can easily autowire a generic bean and have Spring find it safely, even if the container bean is generic.
E.g. the following work (see also)
class MyBean {
@Autowired
private Dao<Entity> dao;
}
class MyBean<T> {
@Autowired
private Dao<T> dao;
}
However I sometimes need to retrieve beans at runtime during method execution instead of relying on autowiring (e.g. the beans may not be ready yet during context initialization)
private myCode() {
BeanFactory beanFactory; //or ConfigurableListableBeanFactory too
Dao<Entity> dao = beanFactory.getBean(....????....);
}
Considerations:
- BeanFactory.getBean accepts a bean name and/or a type argument. I could or could not know the bean's name at runtime
- Dao.class resolves to any generic implementation of Dao (e.g. Dao and Dao)
Questions is:
How do I invoke BeanFactory to get a bean instance that is bound to a given type?
Related: I know that Spring's RestTemplate
requires a ParameterizedTypeReference when you need to bind a call to a return type of List<T>
(when you know T)