自己简单封装spring容器

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

/**
 * 服务提供核心类
 * 该类的主要作用是加载beans.xml文件
 * @author grace
 *
 */
public class ServiceProvinderCore {
	
	protected ApplicationContext ctx;
	/**
	 * @param filename beans.xml
	 */
	public void load(String filename){
		ctx=new ClassPathXmlApplicationContext(filename);
	}
}


import org.apache.commons.lang.xwork.StringUtils;


public class ServiceProvinder {

	private static ServiceProvinderCore sc;
	
//	封装方法:
//	ApplicationContext ctx=new ClassPathXmlApplicationContext("beans.xml");
//	静态方法,一调用该类就执行该方法
	static{
		sc=new ServiceProvinderCore();
		sc.load("beans.xml");
	}
	
//	封装方法:
//	ISysUserGroupService sysUserGroupService=(ISysUserGroupService) ctx.getBean(ISysUserGroupService.SERVICE_NAME);
	public static Object getService(String beanName){
		if(StringUtils.isBlank(beanName)){
			throw new RuntimeException("您要访问的服务名称不能为空");
		}
		Object bean=null;
		//如果spring容器中包含beanName
		if(sc.ctx.containsBean(beanName)){
			bean=sc.ctx.getBean(beanName);
		}
		
		//如果spring容器中不包含beanName
		if(bean==null){
			throw new RuntimeException("您要访问的服务名称["+beanName+"]不存在");
		}
		return bean;
	}
}



测试类:

import java.util.List;

import org.junit.Test;
import cn.grace.container.ServiceProvinder;
import cn.grace.domain.SysUserGroup;
import cn.grace.service.ISysUserGroupService;

public class TestSysUserGroupService {

	@Test
	public void testSave() {
//		使用自己封装的spring容器拿到service
		ISysUserGroupService sysUserGroupService=(ISysUserGroupService)ServiceProvinder.getService(ISysUserGroupService.SERVICE_NAME);
//		原本的方法
//		ApplicationContext ctx=new ClassPathXmlApplicationContext("beans.xml");
//		ISysUserGroupService sysUserGroupService=(ISysUserGroupService) ctx.getBean(ISysUserGroupService.SERVICE_NAME);
		
		SysUserGroup sysUserGroup = new SysUserGroup();
		sysUserGroup.setName("销售部");
		sysUserGroup.setPrincipal("xxx");
		sysUserGroup.setIncumbent("ttt");
		sysUserGroupService.saveSysUserGroup(sysUserGroup);
	}
}

public interface ISysUserGroupService {
	public final static String  SERVICE_NAME="cn.grace.service.impl.SysUserGroupServiceImpl";
}


优点:

1.操作方便,通过ServiceProvinder.getService(beanName);直接拿到service.

2.如果请求的beanName不合法,通过异常可以看到效果。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员囧辉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值