1 package com.demo; 2 3 import org.springframework.beans.BeansException; 4 import org.springframework.context.ApplicationContext; 5 import org.springframework.context.ApplicationContextAware; 6 import org.springframework.stereotype.Component; 7 8 @Component 9 public class SpringUtils implements ApplicationContextAware { 10 private static ApplicationContext applicationContext = null; 11 12 @Override 13 public void setApplicationContext(ApplicationContext arg0) throws BeansException { 14 if (SpringUtils.applicationContext == null) { 15 SpringUtils.applicationContext = arg0; 16 } 17 } 18 19 // 获取applicationContext 20 public static ApplicationContext getApplicationContext() { 21 return applicationContext; 22 } 23 24 // 通过name获取 Bean. 25 public static Object getBean(String name) { 26 return getApplicationContext().getBean(name); 27 } 28 29 // 通过class获取Bean. 30 public static <T> T getBean(Class<T> clazz) { 31 return getApplicationContext().getBean(clazz); 32 } 33 34 // 通过name,以及Clazz返回指定的Bean 35 public static <T> T getBean(String name, Class<T> clazz) { 36 return getApplicationContext().getBean(name, clazz); 37 } 38 39 }
与Spring Boot启动类同包或其子包