Spring-配置文件加載工具

在Spring的開發中,我們需要加載beans.xml配置文件,在ssh、ssm、ssm2的開發中,面對多個配置文件時,我們使用監聽進行加載,在使用@Autowrited開發時我們不必考慮這一問題,但是在使用手動加載時,我們則需要手動對配置文件進行加載,這是很麻煩的,同時這也加大了資源的消耗,那麼我們該如何改進呢,我們可以使用工具類進行一次性加載,在使用的時候進行調用即可。


1、編寫加載配置文件的類

package com.sw.container;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/*
 *@Author swxctx
 *@time 2017年5月15日
 *@Explain:服務類,用用戶加載applicationContext.xml文件
 */
public class ServiceProvideCord {
	
	protected static ApplicationContext applicationContext;
	
	public static void load(String[] fileName){
		applicationContext = new ClassPathXmlApplicationContext(fileName);
	}
}

2、獲取bean

package com.sw.container;

import org.apache.commons.lang.StringUtils;

/*
 *@Author swxctx
 *@time 2017年5月15日
 *@Explain:Service層服務類
 */
@SuppressWarnings("static-access")
public class SwServiceProvider {
	private static ServiceProvideCord serviceProvideCord;
	
	//靜態加載
	static{
		serviceProvideCord = new ServiceProvideCord();
		serviceProvideCord.load(new String[]{"classpath:/spring/applicationContext-service.xml",
				"classpath:/spring/applicationContext-dao.xml",
				"classpath:/spring/applicationContext-transaction.xml"});
	}
	
	public  static Object getService(String serviceName){
		//服務名稱爲空
		if(StringUtils.isBlank(serviceName)){
			throw new RuntimeException("當前服務名稱不存在...");
		}
		Object object = null;
		if(serviceProvideCord.applicationContext.containsBean(serviceName)){
			//獲取bean
			object = serviceProvideCord.applicationContext.getBean(serviceName);
		}
		if(object==null){
			throw new RuntimeException("服務名稱爲【"+serviceName+"】下的服務節點不存在...");
		}
		return object;
	}
}

在這裏呢,我通過工具類加載了三個配置文件,那麼該如何使用呢?

在applcationContext-dao.xml配置文件中有一個方法bean,那麼在service層實現類中我們需要調用它,我們使用工具類進行調用,如下所示:

@Override
	public String findLoginCheck(String username) throws Exception {
		UserMapper userMapper=(UserMapper) SwServiceProvider.getService("userMapper");
		String pass = userMapper.findPassByName(username);
		return pass;
	}

如上代碼所示,通過SwServiceProvider對bean進行獲取,bean的名字爲userMapper,從而對進行相關的操作。
發佈了436 篇原創文章 · 獲贊 106 · 訪問量 57萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章