Create a bean of type Set <Class <? >>

How can I create a bean of type Class?

I found a way to use getClass (), but it requires an instance and cannot be used with a factory method as it is not static. This also requires a foreign bean:

<bean id="foo" class="Foo" />
<bean id="fooClass" factory-bean="foo" factory-method="getClass" />

      

It's not so bad if Foo is easy to build, but what if the constructor needs parameters?

Then I need to create a set of classes to connect to another bean via a property. I would create a Set, for example:

<util:set id="classSet">
    <ref local="fooClass"/>
</util:set>

      

+2


source to share


2 answers


If you really want to do what you described, you can do it like this:

<bean id="myClass" class="java.lang.Class" factory-method="forName">
   <constructor-arg value="com.MyClass"/>
</bean>

      



But as @ ChssPly76 said, if you want to insert it into another bean, you only need to enter the class name and Spring will automatically convert it to a class instance for you.

+5


source


Why do you need? Can you give an example where this is really needed?

If you only need it as a dependency (for example, some other bean has a property of type Class), Spring's built-in ClassEditor will convert a regular string to an instance of a class with that name for you:



<property name="someClass" value="java.lang.String"/>

      

The above will result in a call setSomeClass(Class clazz)

being called on the bean that has.

+4


source







All Articles