1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| @Component public class ApplicationContextProvider implements ApplicationContextAware, DisposableBean { private static ApplicationContext context;
@Override public void setApplicationContext(ApplicationContext applicationContext) { ApplicationContextProvider.context = applicationContext; }
public static ApplicationContext getApplicationContext() { return context; }
@SuppressWarnings("unchecked") public static <T> T getBean(String name) { assertContextInjected(); return (T) context.getBean(name); }
public static <T> T getBean(Class<T> requiredType) { assertContextInjected(); return context.getBean(requiredType); }
public static <T> T getBean(String name, Class<T> requiredType) { assertContextInjected(); return context.getBean(name, requiredType); }
public static void clearHolder() { context = null; }
@Override public void destroy() { clearHolder(); }
private static void assertContextInjected() { if (context == null) { throw new IllegalStateException("applicaitonContext属性未注入, 请在applicationContext.xml中定义SpringContextHolder或在SpringBoot启动类中注册SpringContextHolder."); } } }
|