動態註冊Bean到Spring容器是很簡單的,咱們只要繼承BeanDefinitionRegistryPostProcessorjava
@Component public class TestDynamicRegistBean implements BeanDefinitionRegistryPostProcessor { @Override public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { System.out.println("yzy:TestDynamicRegistBean.postProcessBeanDefinitionRegistry"); GenericBeanDefinition beanDefinition = new GenericBeanDefinition(); beanDefinition.setBeanClass(User.class); beanDefinition.getPropertyValues().add("name", "yangzhongyu"); registry.registerBeanDefinition("user", beanDefinition); } }
還能夠重載postProcessBeanFactory來完成一樣的事情,註冊User user 到Spring容器。ide
@Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException{ System.out.println("yzy:TestDynamicRegistBean.postProcessBeanFactory"); GenericBeanDefinition beanDefinition = new GenericBeanDefinition(); beanDefinition.setBeanClass(User.class); beanDefinition.getPropertyValues().add("age", "yangzhongyu"); ((DefaultListableBeanFactory) beanFactory) .registerBeanDefinition("user", beanDefinition); }
MyBatis,Dubbo等採用了這個技術來實現Bean的動態註冊.post