自己简单封装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不合法,通过异常可以看到效果。



自己简单封装spring容器,布布扣,bubuko.com

自己简单封装spring容器

上一篇:Jquery中对checkbox的各种“全选”或者“取消”功能实现(特别注意1.6+的一定不能使用attr来取属性了!用prop!)


下一篇:安装Symantec Backup Exec报“microsoft visual C++ 2005 SP1 command line syntax error.”