編寫一個工具類java
實現spring 的ApplicationContextAware接口web
代碼以下:spring
package com.evideostb.billsystem.utils; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * 以靜態變量保存Spring ApplicationContext, 可在任何代碼任何地方任什麼時候候中取出ApplicaitonContext. * @author zhangchuanzhao * 2016-6-12 上午11:04:46 */ public class SpringContextHolder implements ApplicationContextAware { private static ApplicationContext applicationContext; /** * 實現ApplicationContextAware接口的context注入函數, 將其存入靜態變量. */ public void setApplicationContext(ApplicationContext applicationContext) { SpringContextHolder.applicationContext = applicationContext; // NOSONAR } /** * 取得存儲在靜態變量中的ApplicationContext. */ public static ApplicationContext getApplicationContext() { checkApplicationContext(); return applicationContext; } /** * 從靜態變量ApplicationContext中取得Bean, 自動轉型爲所賦值對象的類型. */ @SuppressWarnings("unchecked") public static <T> T getBean(String name) { checkApplicationContext(); return (T) applicationContext.getBean(name); } /** * 從靜態變量ApplicationContext中取得Bean, 自動轉型爲所賦值對象的類型. */ @SuppressWarnings("unchecked") public static <T> T getBean(Class<T> clazz) { checkApplicationContext(); return (T) applicationContext.getBeansOfType(clazz); } /** * 清除applicationContext靜態變量. */ public static void cleanApplicationContext() { applicationContext = null; } @SuppressWarnings("resource") private static void checkApplicationContext() { new ClassPathXmlApplicationContext("SpringMVC-servlet.xml"); if (applicationContext == null) { throw new IllegalStateException( "applicationContext未注入,請在applicationContext.xml中定義SpringContextHolder"); } } }
而後須要在application中把把org.springframework.context.ApplicationContext做爲屬性注入給類app
其實只須要這樣寫就能夠以下:ide
<bean class="com.evideostb.billsystem.utils.SpringContextHolder" lazy-init="false" />
這樣子就是被注入進去了函數
運行的時候只須要加載你的applicationContext.xml工具
*普通java類main方法這樣調用code
new ClassPathXmlApplicationContext("applicationContext.xml");xml
CommonService commonService = (CommonService) SpringContextHolder.getBean("commonService");對象
*web工程直接調用
CommonService commonService = (CommonService) SpringContextHolder.getBean("commonService");