ktm5124
ktm5124

Reputation: 12123

Spring: Injecting an Array or List of some type into a bean

If I have an interface I, and some classes that implement it, is it possible to inject an array I[] or List<I> into a bean? I see that it can be done for List<Object> using <list></list>, but I would like to parametrize my list here - either that or get an array of type I.

The number of elements in the list/array is fixed and determined before runtime.

Thanks for any feedback in advance :-)

Upvotes: 3

Views: 6744

Answers (3)

Michail Nikolaev
Michail Nikolaev

Reputation: 3775

I Spring 3.1 it is possible to inject it as:

@Inject
List<I> list;

where I is your interface (but it should be concrete).

Or you could use Spring Java Config (@Configuration) to produce (@Bean) named lists and inject them using Qualifier or @Named.

Also you may define typed named list as here:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/util    http://www.springframework.org/schema/util/spring-util-2.5.xsd">


<util:list id="myList" value-type="java.lang.String">
    <value>foo</value>
    <value>bar</value>
</util:list>

Upvotes: 2

ach
ach

Reputation: 6234

If you're wanting dynamic auto-wiring based on the generic type then no, due to type erasure. If you just want to wire a list defined as type List<String> (or whatever), there is nothing preventing you from doing that, for example:

Application Context:

<util:list id="theList">
    <value>a</value>
    <value>b</value>
</util:list>

Java class:

@Resource(name = "theList")
List<String> theList;  

This would provide no type safety, though.

Upvotes: 0

emd
emd

Reputation: 750

Thats impossible to achieve because of JAVA type erasure on compile time. The JAVA generics are only available at compile time and are there to ensure type safety. In runtime there are only Object's(references) left.

The only thing you can do to assure type safety (but still runtime) is to have an array of any type and use spring <array></array> or <list></list> tags to populate the data. Then at runtime you will get an exception when you try to populate a Integer[] with Strings.

If you use generics you can have Set<Integer> and in run time end up with Set<String> because of the mentioned type erasure.

Upvotes: 0

Related Questions