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.
@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 .
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.
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With