A colleague of mine just had an interesting problem. Assume a generic class
namespace MyNamespace { public class MyGeneric<T> private string name; public String Name { get { return name; } set { name = value; } } ... } }
Now if you want to create an object of this type via spring, you just specify the following in the app context (assuming that this class resides inside MyAssembly.dll):
<object id="myGeneric" type="MyNamespace.MyGeneric<int>, MyAssembly"> <property name="Name" value="My Generic Class with int"/> </object>
Note that the xml notation for less-than in MyNamespace.MyGeneric<int is not a typo: spring really requires this to be specified this way. Now, suppose that you don’t want to use an int but a custom type as the generic type, let’s say
namespace MyOtherNamespace { public class MyClass { ... } }
If this type resides in the same assembly, you can just say
<object id="myOtherGeneric" type="MyNamespace.MyGeneric<MyOtherNamespace.MyClass>, MyAssembly"> <property name="Name" value="My Generic Class with int"/> </object>
However, if the class of the generic type sits in another assembly, you have to use a workaround. Just adding the assembly after the type won’t work, as the comma is used as the delimiter for multiple generic type arguments. Luckily, spring supports something called a TypeAlias, which, as the name implies, let’s us define an alias for a type. First define the alias
<typeAliases> <alias name="MyClass" type="MyOtherNameSpace.MyClass, MyOtherAssembly" /> </typAliases>
With this type alias defined, we can now define the object as
<object id="myOtherGeneric" type="MyNamespace.MyGeneric<MyClass>, MyAssembly"> <property name="Name" value="My Generic Class with int"/> </object>
May 23, 2007 at 11:39 am
There is a space missing:
October 3, 2007 at 12:19 pm
The same colleague says thanks for blogging it after running into the same issue more than a year later.
🙂
September 5, 2008 at 4:00 pm
Don’t forget people in XML when you want to use greater than less than signs to use
< >
so:
…
October 6, 2008 at 1:59 pm
Thanks! Exactly what I was trying to find out.
July 23, 2009 at 9:18 pm
Thanks! I went with a different approach earlier but this would help me with a permanent solution.