Last active
April 30, 2019 05:35
-
-
Save logicjwell/6403c8bee0233a44c0d73aa7f9a9dd22 to your computer and use it in GitHub Desktop.
[SpringContextUtils] 在非spring管理bean中读取spring上下文里的bean #spring #上下文
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* * | |
* | |
* @Description Spring的ApplicationContext的持有者,可以用静态方法的方式获取spring容器中的bean | |
* @Date 21:07 2018/4/18 | |
*/ | |
@Component | |
public class SpringContextHolder implements ApplicationContextAware { | |
private static ApplicationContext applicationContext; | |
@Override | |
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { | |
SpringContextHolder.applicationContext = applicationContext; | |
} | |
public static ApplicationContext getApplicationContext() { | |
assertApplicationContext(); | |
return applicationContext; | |
} | |
@SuppressWarnings("unchecked") | |
public static <T> T getBean(String beanName) { | |
assertApplicationContext(); | |
return (T) applicationContext.getBean(beanName); | |
} | |
public static <T> T getBean(Class<T> tClass) { | |
assertApplicationContext(); | |
return (T) applicationContext.getBean(tClass); | |
} | |
private static void assertApplicationContext() { | |
if (null == SpringContextHolder.applicationContext) { | |
throw new RuntimeException("applicationContext为空,请检查是否注入springContextHolder"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment