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万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章