user3627600
user3627600

Reputation: 1

How can I inject a Class of an object, not an object itself

I'm trying to inject a list of Class. I want a list of classes, not objects.

My class looks like this:

public class CodeServiceImpl{

    private List<Class<?>> codeList;

// getter and setter

My spring configuration file (I'm not using annotations but xml) is

<bean id="myCodeServiceImpl" class = "net.croz.service.CodeServiceImpl">
        <property name="codeList">
            <list>
                <ref bean="myAddress"/>
                <ref bean="myCity"/>
                <ref bean="myCountry"/>
            </list>
        </property>
    </bean>


    <bean id="myAddress" class="java.lang.Class" factory-method="forName">
            <constructor-arg value="net.croz.model.Address"/> 
        </bean>

        <bean id="myCity" class="java.lang.Class" factory-method="forName">
            <constructor-arg value="net.croz.model.City"/> 
        </bean>

        <bean id="myCountry" class="java.lang.Class" factory-method="forName">
            <constructor-arg value="net.croz.model.Country"/>
        </bean>

But the list codeList isn't being populated. It ends up being a null object. Thank you for your help.

Upvotes: 0

Views: 218

Answers (1)

Artem Bilan
Artem Bilan

Reputation: 121272

Actually it works as is:

<bean class="com.my.proj.Foo">
        <constructor-arg value="java.lang.String, org.springframework.util.StringUtils, byte[]"/>
</bean>

where Foo is:

public class Foo {

    private final List<Class<?>> codeList;

    public Foo(Class<?>... codeList) {
        this.codeList = Arrays.asList(codeList);
    }

}

The ConversionService does the stuff for converting comma-separated string to the Class<?>[] and tries to resolve each class on its own using BeanClassLoader

Upvotes: 1

Related Questions