Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring: how to get an applicable generic bean instance by its type argument(s)?

I'm 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 obtain them in a static way like the following:

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 bean instances (fooService and barService). So I need to pass type arguments somehow.

Is there any way to do this? Something like this:

@SupressWarnings("unchecked")
Service<Foo> service = applicationContext.getGenericBean(
        Service.class, // bean class
        Foo.class // type arguments
        // ...
);
like image 307
Victor Avatar asked Oct 31 '22 14:10

Victor


1 Answers

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're interested in a mechanism to handle generic objects with particular handler.

like image 88
Radu Avatar answered Nov 15 '22 05:11

Radu