Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save xie-qianyue/af3f07894a9b67e2d254123217fd8456 to your computer and use it in GitHub Desktop.
Save xie-qianyue/af3f07894a9b67e2d254123217fd8456 to your computer and use it in GitHub Desktop.
Spring - Register bean by BeanFactoryPostProcessor
public class BeanFactoryPostProcessorExample {
public static void main (String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(MyConfig.class);
MyBean bean = context.getBean(MyBean.class);
bean.doSomething();
}
}
public class MyBean {
private String strProp;
public void setStrProp (String strProp) {
this.strProp = strProp;
}
public void doSomething () {
System.out.println("from MyBean: " + strProp);
}
}
@Configuration
public class MyConfig {
@Bean
MyConfigBean myConfigBean () {
return new MyConfigBean();
}
}
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