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.example.zuul.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.example.zuul.feign.PayClient", beanDefinitionBuilder.getRawBeanDefinition());
Object bean = SpringContextUtils.getBean(PayClient.class);
package com.example.zuul;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* 获取ApplicationContext和Object的工具类
*/
@Component
@SuppressWarnings({ "rawtypes", "unchecked" })
public class SpringContextUtils implements ApplicationContextAware {
private static ApplicationContext applicationContext;
/**
* 实现ApplicationContextAware接口的context注入函数, 将其存入静态变量.
*/
public void setApplicationContext(ApplicationContext applicationContext) {
SpringContextUtils.applicationContext = applicationContext; // NOSONAR
}
/**
* 取得存储在静态变量中的ApplicationContext.
*/
public static ApplicationContext getApplicationContext() {
checkApplicationContext();
return applicationContext;
}
private static void checkApplicationContext() {
if (applicationContext == null) {
throw new IllegalStateException("applicaitonContext未注入,请在applicationContext.xml中定义SpringContextHolder");
}
}
/**
* 获取bean
*
* @param name bean的id
* @param <T>
* @return
*/
public static <T> T getBean(String name) {
return (T) applicationContext.getBean(name);
}
//通过类型获取上下文中的bean
public static Object getBean(Class<?> requiredType) {
return applicationContext.getBean(requiredType);
}
}