spring获取所有被装配类工具
工具类代码
1 /** 2 * 获取所有被装配的类 3 * @author missY 4 * @date 2019-07-03 5 */ 6 @Component 7 public class SpringUtil implements ApplicationContextAware { 8 9 private static ApplicationContext applicationContext;//当前IOC 10 11 /** 12 * 设置applicationContext 13 */ 14 @Override 15 public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { 16 SpringUtil.applicationContext = applicationContext; 17 } 18 19 /** 20 * 从当前IOC获取bean 21 */ 22 public static <T> T getObject(Class<T> clazz) { 23 return applicationContext.getBean(clazz); 24 } 25 26 //测试用 27 public static void showClass() { 28 String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames(); 29 for (String beanDefinitionName : beanDefinitionNames) { 30 System.out.println(beanDefinitionName); 31 } 32 } 33 34 }
调用示例
YourObject yourObject = SpringUtil.getObject(YourObject.class);