Passing parameter into Spring factory bean factory method

Paulius Matulionis picture Paulius Matulionis · Sep 4, 2012 · Viewed 7.2k times · Source

I have a Spring bean which is declared like this:

<osgi:reference id="basicAuthSecurityHandler" interface="com.groupgti.handler.authentication.basic.Handler"/>
<bean id="securityHandler" factory-bean="basicAuthSecurityHandler" factory-method="getSecurityHandler"/>

My getSecurityHandler method looks like this:

public ConstraintSecurityHandler getSecurityHandler(String realm) {
    ConstraintSecurityHandler handler =(ConstraintSecurityHandler) factory.getBean("securityHandler");
    handler.setRealmName(realm);
    return handler;
}

This securityHandler bean is in scope prototype. I need to pass the parameter into getSecurityHandler method when it it constructed with spring. Is this even possible? I can't find any documentation about it.

Answer

Paulius Matulionis picture Paulius Matulionis · Sep 4, 2012

The only way I got it working is this:

<osgi:reference id="basicAuthSecurityHandler" interface="com.groupgti.handler.authentication.basic.Handler"/>

<bean id="securityHandler" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    <property name="targetObject" ref="basicAuthSecurityHandler"/>
    <property name="targetMethod" value="getSecurityHandler"/>
    <property name="arguments">
        <list>
            <value type="java.lang.String">${com.groupgti.esb.targetjobs.indeed.userRealm}</value>
        </list>
    </property>
</bean>

I had to use MethodInvokingFactoryBean. I have tried to use constructor-arg, but then I got the exception that there is no such constructor. Using MethodInvokingFactoryBean everything works fine.