Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining spring bean using a class with generic parameters

If I have a class that looks something like this:

public class MyClass<T extends Enum<T>> {   public void setFoo(T[] foos) {     ....   } } 

How would I go about declaring this as a bean in my context xml so that I can set the Foo array assuming I know what T is going to be (in my example, let's say T is an enum with the values ONE and TWO)?

At the moment, having something like this is not enough to tell spring what the type T is:

<bean id="myClass" class="example.MyClass">   <property name="foo">     <list>       <value>ONE</value>       <value>TWO</value>     </list>   </property> </bean> 

Edit: Forgot the list tag.

like image 280
digiarnie Avatar asked Apr 28 '09 23:04

digiarnie


People also ask

Is @bean a class level annotation?

@Bean is a method-level annotation and a direct analog of the XML <bean/> element. The annotation supports most of the attributes offered by <bean/> , such as: init-method , destroy-method , autowiring , lazy-init , dependency-check , depends-on and scope .

What is @configuration and @bean in Spring?

Annotating a class with the @Configuration indicates that the class can be used by the Spring IoC container as a source of bean definitions. The @Bean annotation tells Spring that a method annotated with @Bean will return an object that should be registered as a bean in the Spring application context.

How do you define generic classes?

A Generic class simply means that the items or functions in that class can be generalized with the parameter(example T) to specify that we can add any type as a parameter in place of T like Integer, Character, String, Double or any other user-defined type.

What are different ways to configure a class as Spring bean?

There are 3 different ways to configure a class as Spring Bean. XML Configuration is the most popular configuration. The bean element tag is used in xml context file to configure a Spring Bean. Using Java Based Configuration, you can configure a Spring bean using @Bean annotation.


1 Answers

Spring has no generic support for that case, but the compiler just creates a class cast in this case. So the right solution is:

<bean id="myClass" class="example.MyClass">   <property name="foo">     <list value-type="example.MyEnumType">       <value>ONE</value>       <value>TWO</value>     </list>   </property> </bean> 
like image 60
Arne Burmeister Avatar answered Oct 10 '22 12:10

Arne Burmeister