获取并打印Spring容器中所有的Bean名称
思路:
1.实现Spring的ApplicationContextAware接口,重写setApplicationContext方法,将得到的ApplicationContext对象保存到一个静态变量中,有了这个上下文对象,就可以在项目的任意地方用它来得到任意Bean;
2.调用applicationContext.getBeanDefinitionNames()方法就可以拿到Spring容器中所有的Bean名称;这里为了测试方便就直接在InitializingBean 接口的afterPropertiesSet方法中打印所有Bean名称;启动Spring容器,观察控制台即可看到打印结果,打印Spring容器中所有bean在项目调试的时候很有用。
1 import org.springframework.beans.BeansException; 2 import org.springframework.beans.factory.InitializingBean; 3 import org.springframework.context.ApplicationContext; 4 import org.springframework.context.ApplicationContextAware; 5 import org.springframework.stereotype.Component; 6 7 /** 8 * 打印Spring容器所有的Bean名称 9 * 10 * @author syj 11 */ 12 @Component 13 public class ApplicationContextBean implements ApplicationContextAware, InitializingBean { 14 15 public static ApplicationContext applicationContext; 16 17 /** 18 * 获取 ApplicationContext 19 * 20 * @param applicationContext 21 * @throws BeansException 22 */ 23 @Override 24 public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { 25 ApplicationContextBean.applicationContext = applicationContext; 26 } 27 28 /** 29 * 打印IOC容器中所有的Bean名称 30 * 31 * @throws Exception 32 */ 33 @Override 34 public void afterPropertiesSet() throws Exception { 35 String[] names = applicationContext.getBeanDefinitionNames(); 36 for (String name : names) { 37 System.out.println(">>>>>>" + name); 38 } 39 System.out.println("------\nBean 总计:" + applicationContext.getBeanDefinitionCount()); 40 } 41 }
还有一种更简单的方式,直接使用@Autowired注入ApplicationContext对象:
1 import org.springframework.beans.factory.annotation.Autowired; 2 import org.springframework.context.ApplicationContext; 3 import org.springframework.web.bind.annotation.GetMapping; 4 import org.springframework.web.bind.annotation.RequestMapping; 5 import org.springframework.web.bind.annotation.RestController; 6 7 import java.util.Arrays; 8 import java.util.List; 9 10 @RestController 11 @RequestMapping 12 public class BeanController { 13 14 @Autowired 15 private ApplicationContext applicationContext; 16 17 @GetMapping("/beanList") 18 public List<String> beanList() { 19 return Arrays.asList(applicationContext.getBeanDefinitionNames()); 20 } 21 }