在Spring中可以通过ContextLoader
获取上下文环境
WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
但是这种方式在Spring Boot是失效的。本文提供三种方案获取Spring Boot上下文环境。
-
自动注入
@Autowired WebApplicationContext webApplicationConnect;
-
实现
ApplicationContextAware
接口/** * spring bean 工具类 * * @author simon * @create 2018-09-10 9:51 **/ @Component public class SpringBeanTool implements ApplicationContextAware { /** * 上下文对象实例 */ private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } /** * 获取applicationContext * * @return * applicationContext */ public static ApplicationContext getApplicationContext() { return applicationContext; } /** * 通过name获取 Bean. * * @param name * bean name * @return * bean */ public static Object getBean(String name){ return getApplicationContext().getBean(name); } /** * 通过class获取Bean. * @param clazz * class * @param <T> * @return */ public static <T> T getBean(Class<T> clazz){ return getApplicationContext().getBean(clazz); } /** * 通过name,以及Clazz返回指定的Bean * @param name * bean name * @param clazz * class * @param <T> * @return * bean */ public static <T> T getBean(String name,Class<T> clazz){ return getApplicationContext().getBean(name, clazz); } }
-
在启动类中设置
public class SpringBeanTool { private static ApplicationContext applicationContext; public static ApplicationContext getApplicationContext(){ return applicationContext; } public static void setApplicationContext(ApplicationContext applicationContext){ SpringContextUtil.applicationContext = applicationContext; } public static <T> T getBean(String name){ return (T)applicationContext.getBean(name); } public static <T> T getBean(Class<T> clazz){ return applicationContext.getBean(clazz); } }
启动类:
public static void main(String[] args) { ApplicationContext context = SpringApplication.run(Application.class, args); SpringBeanTool.setApplicationContext(context); }
网友评论