自造spring容器&&web.xm

阅读更多
1.自造spring容器
package cn.wxg.elec.container;

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

/**
*获取spring配置文件,初始化applicationContext对象
*/
public class ServiceProviderCord {

protected static ApplicationContext ac;

public static void load(String filename){
ac = new ClassPathXmlApplicationContext(filename);
}
}

package cn.wxg.elec.container;

import org.apache.commons.lang.StringUtils;

/*
*调用核心类对象,使用静态代码块,初始化一次spring配置
*/
public class ServiceProvider {

public static ServiceProviderCord spc;
//加载beans.xml文件
static{
spc = new ServiceProviderCord();
spc.load("beans.xml");
System.out.println("##############################################################");
}

public static Object getService(String serviceName){
if(StringUtils.isBlank(serviceName)){
throw new RuntimeException("当前服务名称不存在");
}
Object object = null;
if(spc.ac.containsBean(serviceName)){
object = spc.ac.getBean(serviceName);
}
if(object==null){
throw new RuntimeException("当前服务名称【"+serviceName+"】下的服务节点不存在");
}
return object;
}
}

2.使用web.xml配置初始化spring配置

contextConfigLocation
/WEB-INF/myApplicationContext.xml


你可能感兴趣的:(自造spring容器&&web.xm)