2011-09-13 9 views

Respuesta

10

No, no puedes. Si necesita parámetros, deberá insertarlos como campos de antemano.

bean de ejemplo XML

public class Foo{ 

    @Autowired 
    private Bar bar; 

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

} 

muestra:

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

Ok, gracias por la información – Radu

2

Este método es especialmente útil cuando no se puede cambiar la clase que usted está tratando de crear como en la respuesta anterior, sino que está más bien trabajar con una API y debe usar el bean proporcionado tal como está.

Siempre se puede crear una clase (MyObjectFactory) que implementa FactoryBean y dentro del método getObject() debe escribir:

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

Y en la primavera context.xml que tendría un simple:

<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(); 
    } 
} 

véase el código cómoda de fuente de primavera en Method initMethod = BeanUtils.findMethod(bean.getClass(), initMethodName, null); el método init es encontrar y parámetro es nulo

Cuestiones relacionadas