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);
}
}