从应用程序上下文中删除Spring Bean

时间:2016-08-05 16:12:46

标签: java spring spring-boot

我使用下面的内容显示上下文中的所有spring bean。如何从上下文中删除bean?

 ConfigurableApplicationContext ctx = SpringApplication.run(ProxyApplication.class, args);
 for(String beanName:ctx.getBeanDefinitionNames()){
     System.out.println(beanName);
 }

1 个答案:

答案 0 :(得分:5)

你可以这样做:

    ConfigurableApplicationContext ctx = SpringApplication.run(ProxyApplication.class, args);
    BeanDefinitionRegistry registry = (BeanDefinitionRegistry) ctx.getAutowireCapableBeanFactory();
    for(String beanName : ctx.getBeanDefinitionNames()){
        System.out.println(beanName);
        registry.removeBeanDefinition(beanName);
    }