新建一個類實現ApplicationContextAware,便可獲取ApplicationContext,而後寫get方法獲取相應的bean,代碼以下:ide
@Component public class SpringContextHolder implements ApplicationContextAware{ private static ApplicationContext context; public static ApplicationContext getContext() { return context; } public static Object getBean(String beanName) { return context.getBean(beanName); } public static <T> T getBean(Class<T> beanClass) { return context.getBean(beanClass); } @Override public void setApplicationContext(ApplicationContext paramApplicationContext) throws BeansException { context=paramApplicationContext; } }