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,从而对进行相关的操作。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值