javaspringgenerics

Get spring bean via context using generic


I have a bunch of repository beans that implement type Repository<T extends Node>. Now I can get a list of random nodes from the user and I want to get the appropriate repository for each node. Since Spring 4.0RC1 we can autowire repositories like this:

@Autowired Repository<SomeNode> someNodeRepository;

As documented here.

This works fine, but my question is how I can do this dynamically based on the generic type.

What I want to do is something like:

public <T extends Node> T saveNode(T node) {
    Repository<T> repository = ctx.getBean(Repository.class, node.getClass());
    return repository.save(node);
}

Where the second parameter is the generic type. This of course does not work, although it compiles.

I can't find any/the documentation on this.


Solution

  • You can do something like this:

    String[] beanNamesForType = ctx.getBeanNamesForType(ResolvableType.forClassWithGenerics(Repository.class, node.getClass()));
    
    // If you expect several beans of the same generic type then extract them as you wish. Otherwise, just take the first
    Repository<T> repository = (Repository<T>) ctx.getBean(beanNamesForType[0]);