Close

Spring Framework - GenericBeanDefinition Examples

[Last Updated: Nov 8, 2025]

Spring Framework 

Programmatically registering beans with GenericBeanDefinition

package com.logicbig.example;

import java.util.Date;

public class MyBean {
private Date date;

public void doSomething() {
System.out.println("from my bean, date: " + date);
}

public void setDate(Date date) {
this.date = date;
}
}

package com.logicbig.example;

import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.GenericBeanDefinition;

import java.util.Date;

public class GenericBeanDefinitionExample {

public static void main(String[] args) {
DefaultListableBeanFactory context =
new DefaultListableBeanFactory();

GenericBeanDefinition gbd = new GenericBeanDefinition();
gbd.setBeanClass(MyBean.class);

MutablePropertyValues mpv = new MutablePropertyValues();
mpv.add("date", new Date());

//alternatively we can use:
// gbd.getPropertyValues().addPropertyValue("date", new Date());
gbd.setPropertyValues(mpv);

context.registerBeanDefinition("myBeanName", gbd);

MyBean bean = context.getBean(MyBean.class);
bean.doSomething();
}
}

Output

from my bean, date: Tue Nov 04 23:18:22 CST 2025
Original Post




Injecting a bean instance into another bean, 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();
}
}

Output

from other bean 
Original Post




See Also