Spring initialization parameters

I am new to spring and I wanted to ask if parameters can be passed to the init and destroy bean methods.

Thanks.

+6
source share
3 answers

No, you can’t. If you need parameters, you will have to first enter them as fields.

Bean example

public class Foo{ @Autowired private Bar bar; public void init(){ bar.doSomething(); } } 

XML example:

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

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

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

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

And in spring context.xml you will have a simple:

 <bean id="myObject" class="MyObjectFactory"/> 
+2
source
  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); init method is find and param is null

0
source

Source: https://habr.com/ru/post/897223/


All Articles