首页 > 代码库 > Spring Boot 获取ApplicationContext
Spring Boot 获取ApplicationContext
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 @Override13 public void setApplicationContext(ApplicationContext arg0) throws BeansException {14 if (SpringUtils.applicationContext == null) {15 SpringUtils.applicationContext = arg0;16 }17 }18 19 // 获取applicationContext20 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返回指定的Bean35 public static <T> T getBean(String name, Class<T> clazz) {36 return getApplicationContext().getBean(name, clazz);37 }38 39 }
与Spring Boot启动类同包或其子包
Spring Boot 获取ApplicationContext
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。