1、新建一個類SpringBeanFactoryUtils 實現 ApplicationContextAware
package com.loiot.baqi.utils; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; /** * ------------------------------------------- * Title : SpringBeanFactoryUtils * Description : 普通類調用Spring注解方式的Service層bean * Create on : 2016年11月1日 下午3:12:25 * Copyright (C) strongunion * @author RICK * 修改歷史: * 修改人 修改日期 修改描述 * ------------------------------------------- */ public class SpringBeanFactoryUtils implements ApplicationContextAware { private static ApplicationContext appCtx; /** * TODO: 此方法可以把ApplicationContext對象inject到當前類中作為一個靜態成員變量。 * @Auhor: RICK * @Date : 2016年11月1日 */ public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { appCtx = applicationContext; } /** * TODO: 獲取ApplicationContext * @Auhor: RICK * @Date : 2016年11月1日 */ public static ApplicationContext getApplicationContext() { return appCtx; } /** * TODO: 這是一個便利的方法,幫助我們快速得到一個BEAN * @Auhor: RICK * @Date : 2016年11月1日 */ public static Object getBean(String beanName) { return appCtx.getBean(beanName); } }
2、在spring的配置文件.xml中添加
<bean id="springBeanFactoryUtils" class="com.haier.util.SpringBeanFactoryUtils"/>
3、在普通類中使用service
ZpAccountSalaryHistoryService zpAccountSalaryHistoryService = (ZpAccountSalaryHistoryService)SpringBeanFactoryUtils.getBean("zpAccountSalaryHistoryService");