Search code examples
javaspringcode-injection

Injection of constructor attributes


I'm injecting in a list which will populate a map used within the class.

However when injecting in the flowing attribute:

private List<?> srcSystemIDList;

via the flowing XML:

<bean id="transformerHelper" class="com.common.TransformerHelper">
        <property name="srcSystemIDList" value="#{ T(java.util.Arrays).asList('6','57','92','93','7','108','106','105','98','52','122','9','26','51','101','102','118') }" />
</bean>

which is used by this method to set the map:

    public void srcSystemIDListInit()
{
        Object[] srcSystemArray = srcSystemIDList.toArray();
        int j;
        for(int i = 0; i< srcSystemArray.length; i = i+2)
        {
            j = i + 1;

            if(j < srcSystemArray.length)
            {
                srcSystemIDMap.put(srcSystemArray[i].toString(), srcSystemArray[j].toString());
            }
        }
}

I'm calling this via the constructor.

public TransformerHelper()
{
    srcSystemIDListInit();
} 

However when the constructor calls the method the list is null throwing a null pointer exception.

How can I populate the map via the injected list


Solution

  • You can do as Vikdor says, or you have a couple other approaches you can take too.

    1. You could call this method, not from the constructor, but from your setter method setSrcSystemIDList(...). This will require the least work. (But really, all of these suggestions are quite easy...)
    2. You could implement the InitializingBean interface, and call your method from there.
    3. You could annotate the method with @PostConstruct.
    4. You could add an init-method attribute to your bean xml, which specifies the method to call.