Spring: how to get the applicable generic bean instance by its type argument (s)?
I am using Spring 4.1.2 and I have the following code:
public class Foo {
}
public class Bar {
}
public interface Service<T> {
}
@Service("fooService")
public class FooServiceImpl implements Service<Foo> {
}
@Service("barService")
public class BarServiceImpl implements Service<Bar> {
}
I know that Spring 4 can inject generic bean instances like the following:
@Autowired
private Service<Foo> service; // works fine
But I need to get them statically like this:
Service<Foo> service = getService(getContext(), Foo.class);
...
public static <T> Service<T> getService(ApplicationContext context,
Class<T> objectClass) {
...
}
I tried to use ApplicationContext.getBeansOfType(Service.class)
, but it returns all available copies of the bean ( fooService
and barService
). So I need to pass the type arguments somehow.
Is there a way to do this? Something like that:
@SupressWarnings("unchecked")
Service<Foo> service = applicationContext.getGenericBean(
Service.class, // bean class
Foo.class // type arguments
// ...
);
+3
source to share
1 answer
Getting generic beans programmatically from the application context:
String[] beanNames = applicationContext.getBeanNamesForType(ResolvableType.forType(new ParameterizedTypeReference<String>() {}));
if (beanNames.length > 0) {
String bean = (String) applicationContext.getBean(beanNames[0]);
}
Or check this answer if you are interested in a mechanism for handling shared objects with a custom handler.
0
source to share