Created
June 11, 2018 09:25
-
-
Save xie-qianyue/fbd2e66e0da3b2ace90b60e4fd80a209 to your computer and use it in GitHub Desktop.
Spring - Register Bean by GenericBeanDefinition
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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