java - How to Autowire Bean of generic type <T> in Spring? -


i have bean item<t> required autowired in @configuration class.

@configuration public class appconfig {      @bean     public item<string> stringitem() {         return new stringitem();     }      @bean     public item<integer> integeritem() {         return new integeritem();     }  } 

but when try @autowire item<string>, following exception.

"no qualifying bean of type [item] defined: expected single matching bean found 2: stringitem, integeritem" 

how should autowire generic type item<t> in spring?

simple solution upgrade spring 4.0 automatically consider generics form of @qualifier, below:

@autowired private item<string> stritem; // injects stringitem bean  @autowired private item<integer> intitem; // injects integeritem bean 

infact, can autowire nested generics when injecting list, below:

// inject item beans long have <integer> generic // item<string> beans not appear in list @autowired private list<item<integer>> intitems; 

how works?

the new resolvabletype class provides logic of working generic types. can use navigate , resolve type information. methods on resolvabletype return resolvabletype, example:

// assuming 'field' refers 'intitems' above resolvabletype t1 = resolvabletype.forfield(field); // list<item<integer>>  resolvabletype t2 = t1.getgeneric(); // item<integer> resolvabletype t3 = t2.getgeneric(); // integer class<?> c = t3.resolve(); // integer.class  // or more succinctly class<?> c = resolvabletype.forfield(field).resolvegeneric(0, 0); 

check out examples & tutorials @ below links.

hope helps you.


Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -