獲取spring的例項物件
阿新 • • 發佈:2018-11-08
首先要繼承ApplicationContextAware來獲取上下文:ApplicationContext
public class SpringContextUtils implements ApplicationContextAware { private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) { SpringContextUtils.applicationContext = applicationContext; } // 各種方法獲取例項 public static Object getBean(String beanName) { if (applicationContext != null) return applicationContext.getBean(beanName); return null; } public static <T> T getBean(Class<T> clazz) { if (applicationContext != null) return applicationContext.getBean(clazz); return null; } public static <T> T getBean(String beanName, Class<T> clazz) { if (applicationContext != null) return clazz.cast(getBean(beanName)); return null; }
<bean class="cn.base.mvc.SpringContextUtils" />