开发者

Spring init-method params

I am new to spring and I wanted to ask whether or not it is possible to pass params to the init and destroy methods of a bean.

开发者_运维技巧Thanks.


No, you can't. If you need parameters, you will have to inject them as fields beforehand.

Sample Bean

public class Foo{

    @Autowired
    private Bar bar;

    public void init(){
        bar.doSomething();
    }

}

Sample XML:

<bean class="Foo" init-method="init" />


This method is especially useful when you cannot change the class you are trying to create like in the previous answer but you are rather working with an API and must use the provided bean as it is.

You could always create a class (MyObjectFactory) that implements FactoryBean and inside the getObject() method you should write :

@Autowired
private MyReferenceObject myRef;
public Object getObject()
{
    MyObject myObj = new MyObject();
    myObj.init(myRef);
    return myObj;
}

And in the spring context.xml you would have a simple :

<bean id="myObject" class="MyObjectFactory"/>


    protected void invokeCustomInitMethod(String beanName, Object bean, String initMethodName)
        throws Throwable {

    if (logger.isDebugEnabled()) {
        logger.debug("Invoking custom init method '" + initMethodName +
                "' on bean with beanName '" + beanName + "'");
    }
    try {
        Method initMethod = BeanUtils.findMethod(bean.getClass(), initMethodName, null);
        if (initMethod == null) {
            throw new NoSuchMethodException("Couldn't find an init method named '" + initMethodName +
                    "' on bean with name '" + beanName + "'");
        }
        if (!Modifier.isPublic(initMethod.getModifiers())) {
            initMethod.setAccessible(true);
        }
        initMethod.invoke(bean, (Object[]) null);
    }
    catch (InvocationTargetException ex) {
        throw ex.getTargetException();
    }
}

see spring soruce code in Method initMethod = BeanUtils.findMethod(bean.getClass(), initMethodName, null); the init method is find and param is null


You cannot pass params to init-method but you can still achieve the same effect using this way:

     <bean id="beanToInitialize" class="com.xyz.Test"/>
     <bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
            <property name="targetObject" ref="beanToInitialize" />
            <property name="targetMethod" value="init"/> <!-- you can use any name -->
            <property name="arguments" ref="parameter" /> <!-- reference to init parameter, can be value as well -->
     </bean>

Note: you can also pass multiple arguments as a list using this

<property name="arguments">
      <list>
        <ref local="param1" />
        <ref local="param2" />
      </list>
</property>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜