This example shows how to inject a bean instance into another bean where both beans are registered programmatically.
package com.logicbig.example; public class MyBean { private MyOtherBean otherBean; public void setOtherBean(MyOtherBean otherBean) { this.otherBean = otherBean; } public void doSomething() { otherBean.doSomething(); } }
package com.logicbig.example; public class MyOtherBean { public void doSomething() { System.out.println("from other bean "); } }
package com.logicbig.example; import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.support.GenericBeanDefinition; public class InjectingOtherBeans { public static void main(String[] args) { DefaultListableBeanFactory context = new DefaultListableBeanFactory(); //define and register MyOtherBean GenericBeanDefinition beanOtherDef = new GenericBeanDefinition(); beanOtherDef.setBeanClass(MyOtherBean.class); context.registerBeanDefinition("other", beanOtherDef); //define and register myBean GenericBeanDefinition beanDef = new GenericBeanDefinition(); beanDef.setBeanClass(MyBean.class); MutablePropertyValues mpv = new MutablePropertyValues(); mpv.addPropertyValue("otherBean", context.getBean("other")); beanDef.setPropertyValues(mpv); context.registerBeanDefinition("myBean", beanDef); //using MyBean instance MyBean bean = context.getBean(MyBean.class); bean.doSomething(); } }
from other bean
Dependencies and Technologies Used:
Version compatibilities of spring-context with this example:
Versions in green have been tested.