转自:
下文笔者讲述java代码中打印出所有SpringBean的方法分享,如下所示
实现思路: 方式一: 实现Spring的ApplicationContextAware接口 然后重写setApplicationContext方法 得到的ApplicationContext对象保存到一个静态变量中 此对象中就包含了所有的spring bean 方式二: 调用applicationContext.getBeanDefinitionNames()方法 可获取Spring容器中所有Bean名称
例1:
import org.springframework.beans.BeansException; import org.springframework.beans.factory.InitializingBean; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; /** * 打印Spring容器所有的Bean名称 */ @Component public class ApplicationContextBean implements ApplicationContextAware, InitializingBean { public static ApplicationContext applicationContext; /** * 获取 ApplicationContext * * @param applicationContext * @throws BeansException */ @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { ApplicationContextBean.applicationContext = applicationContext; } /** * 打印IOC容器中所有的Bean名称 * author:www.java265.com * @throws Exception */ @Override public void afterPropertiesSet() throws Exception { String[] names = applicationContext.getBeanDefinitionNames(); for (String name : names) { System.out.println("spring bean名称>>>>>>" + name); } System.out.println("------Bean 总计:" + applicationContext.getBeanDefinitionCount()); } }
方式二:
直接使用@Autowired注入ApplicationContext对象
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.Arrays; import java.util.List; @RestController @RequestMapping public class BeanController { @Autowired private ApplicationContext applicationContext; @GetMapping("/beanList") public List<String> beanList() { return Arrays.asList(applicationContext.getBeanDefinitionNames()); } }