Following example shows how to use GenericBeanDefinition to register an object dynamically.
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; } }
This is where we are going to create GenericBeanDefinition and register it with DefaultListableBeanFactory .
DefaultListableBeanFactory
DefaultListableBeanFactory implements BeanDefinitionRegistry.
BeanDefinitionRegistry
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(); } }
from my bean, date: Tue Nov 04 23:18:22 CST 2025
Dependencies and Technologies Used:
Version compatibilities of spring-context with this example:
Versions in green have been tested.