java手动注入bean到spring容器
ApplicationContext applicationContext = SpringContextUtils.getApplicationContext(); //将applicationContext转换为ConfigurableApplicationContext ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) applicationContext; // 获取bean工厂并转换为DefaultListableBeanFactory DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) configurableApplicationContext.getBeanFactory(); this.defaultListableBeanFactory = defaultListableBeanFactory; String[] beanNamesForType = defaultListableBeanFactory.getBeanNamesForType(PayClient.class); System.out.println("beanNamesForType:" + Arrays.toString(beanNamesForType)); // defaultListableBeanFactory.removeBeanDefinition("com.xxx.feign.PayClient"); defaultListableBeanFactory.removeBeanDefinition(beanNamesForType[0]); // 通过BeanDefinitionBuilder创建bean定义 BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(PayClient.class); // 设置属性userService,此属性引用已经定义的bean:userService,这里userService已经被spring容器管理了. // beanDefinitionBuilder.addPropertyReference("payClient", "payClient"); // 注册bean defaultListableBeanFactory.registerBeanDefinition("com.xxx.feign.PayClient", beanDefinitionBuilder.getRawBeanDefinition()); Object bean = SpringContextUtils.getBean(PayClient.class);