2011-09-13 131 views

回答

10

不,你不能。如果您需要参数,则必须事先将其注入为字段。

样品豆

public class Foo{ 

    @Autowired 
    private Bar bar; 

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

} 

示例XML:

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

好的,谢谢你的信息 – Radu

2

,当你不能改变你想创建在以前的答案类,但你是相当有工作,此方法特别有用一个API并且必须照原样使用提供的bean。

你总是可以创建一个类(MyObjectFactory)实现的FactoryBean和getObject()方法中,你应该写:

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

在春天的context.xml想得简单:

<bean id="myObject" class="MyObjectFactory"/> 
0
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(); 
    } 
} 

看到Spring是soruce代码Method initMethod = BeanUtils.findMethod(bean.getClass(), initMethodName, null); init方法是发现和param为null