Skip to content

Instantly share code, notes, and snippets.

@xie-qianyue
Created June 11, 2018 09:25
Show Gist options
  • Save xie-qianyue/fbd2e66e0da3b2ace90b60e4fd80a209 to your computer and use it in GitHub Desktop.
Save xie-qianyue/fbd2e66e0da3b2ace90b60e4fd80a209 to your computer and use it in GitHub Desktop.
Spring - Register Bean by GenericBeanDefinition
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();
}
}
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;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment