【Java 重新加载bean 上下文 刷新bean】

@Autowired
private ApplicationContext applicationContext;

// 可以为接口或者业务方法被调用
public void reloadInstance(){
	//获取上下文
	DefaultListableBeanFactory defaultListableBeanFactory =
			(DefaultListableBeanFactory)applicationContext.getAutowireCapableBeanFactory();
	//销毁指定实例 wxMpService是上文注解过的实例名称 name="wxMpService" 或没注解情况下默认的bean名称
	defaultListableBeanFactory.destroySingleton("wxMpService");
	//按照旧有的逻辑重新获取实例,WxMpService是我自己逻辑中的类 获取要刷新实例下的bean方法
	WxMpService wxMpService = wxMpService();
	//重新注册同名实例,这样在其他地方注入的实例还是同一个名称,但是实例内容已经重新加载
	defaultListableBeanFactory.registerSingleton("wxMpService",wxMpService);
}

@Bean("wxMpService") 
public static WxMpService wxMpService() {
    ... ... 
}
原文链接:https://blog.csdn.net/Z_hhhha/article/details/123549819

//getAutowireCapableBeanFactory()
//ApplicationContext 无法注入时,请换种方式,如下:

/**
 * @author Joe
 * @date 2022/5/26 16:20
 */
@Configuration
public class AppUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        AppUtil.applicationContext = applicationContext;
    }

    public static DefaultListableBeanFactory getAutowireCapableBeanFactory(){
        DefaultListableBeanFactory defaultListableBeanFactory =
                (DefaultListableBeanFactory)applicationContext.getAutowireCapableBeanFactory();
        return defaultListableBeanFactory;
    }

将ApplicationContext 替换注入此类即可

你可能感兴趣的:(bean,java,开发语言)