Created
June 11, 2018 09:49
-
-
Save xie-qianyue/af3f07894a9b67e2d254123217fd8456 to your computer and use it in GitHub Desktop.
Spring - Register bean by BeanFactoryPostProcessor
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 BeanFactoryPostProcessorExample { | |
public static void main (String[] args) { | |
AnnotationConfigApplicationContext context = | |
new AnnotationConfigApplicationContext(MyConfig.class); | |
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 String strProp; | |
public void setStrProp (String strProp) { | |
this.strProp = strProp; | |
} | |
public void doSomething () { | |
System.out.println("from MyBean: " + strProp); | |
} | |
} |
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
@Configuration | |
public class MyConfig { | |
@Bean | |
MyConfigBean myConfigBean () { | |
return new MyConfigBean(); | |
} | |
} |
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 MyConfigBean implements BeanFactoryPostProcessor { | |
@Override | |
public void postProcessBeanFactory ( | |
ConfigurableListableBeanFactory beanFactory) | |
throws BeansException { | |
GenericBeanDefinition bd = new GenericBeanDefinition(); | |
bd.setBeanClass(MyBean.class); | |
bd.getPropertyValues().add("strProp", "my string property"); | |
((DefaultListableBeanFactory) beanFactory) | |
.registerBeanDefinition("myBeanName", bd); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment