如何在Spring中枚举所有BeanFactories?

时间:2012-02-10 19:43:02

标签: spring

有没有办法以编程方式发现Spring定义的所有BeanFactories。我想创建一个状态调试页面,它打印出spring应用程序上下文中每个bean的名称和类类型,但是我不知道如何获取所有ApplicationContexts的列表。

3 个答案:

答案 0 :(得分:1)

您可以将BeanFactoryPostProcessorApplicationContext联系起来,以便您可以遍历传递的ConfigurableListableBeanFactoryBeanDefinition,这将代表您的所有豆类ApplicationContext

使用此ConfigurableListableBeanFactory实例,您可以找到类型(getBeansOfType())的所有bean,或具有给定注释(getBeansWithAnnotation())的所有bean,等等。

答案 1 :(得分:1)

您可以使用ApplicationContext识别来执行此操作。

      @Component
      public class PrintSpringBeansInContext implements ApplicationContextAware
    {

   private ApplicationContext applicationContext;

        @Override
    public void setApplicationContext(ApplicationContext applicationContext)
        throws BeansException 
     {

      this.applicationContext = applicationContext;
     }


         public void print()
     {
      String[] beanNames = this.applicationContext.getBeanDefinitionNames();
       StringBuilder printBuilder = new StringBuilder("Spring Beans In Context: ");;
    for(String beanName : beanNames)
    {
        printBuilder.append("\n");
        printBuilder.append(" Bean Name: ");
        printBuilder.append(beanName);
        printBuilder.append(" Bean Class: ");
           printBuilder.append(this.applicationContext.getBean(beanName).getClass());
    }
    System.out.println(printBuilder.toString());
}

}

你可以测试一下

  @ContextConfiguration(locations={"classpath:context.xml"})
  @RunWith(SpringJUnit4ClassRunner.class)
  public class PrintContextTest 
  {

   @Autowired
   private PrintSpringBeansInContext service;

   @Test
    public void printBeans()
    {
            Assert.assertNotNull(service);
          service.print();
    }
 }

答案 2 :(得分:1)

下面的代码是一个Spring监听器,它可以在Web应用程序的主spring.xml文件中注册,它构建所有子应用程序上下文的映射,并将此映射公开为属性。下面的类可以使用@Autowired注入任何需要它的spring bean。

import java.util.Hashtable;
import java.util.Map;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ApplicationContextEvent;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.ContextStartedEvent;

public class ContextsApplicationListener implements ApplicationListener<ApplicationContextEvent> {

    private Map<String,ApplicationContext> contextMap = new Hashtable<String,ApplicationContext>();

    @Override
    public void onApplicationEvent(ApplicationContextEvent event) {
        if( event instanceof ContextStartedEvent || event instanceof ContextRefreshedEvent){
            this.getContextMap().put(event.getApplicationContext().getDisplayName(), event.getApplicationContext());
        }

    }

    public Map<String,ApplicationContext> getContextMap() {
        return contextMap;
    }   
}

enter code here