创建spring容器

package com.alibaba.itbu.billing.framework.util;

import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

public class ServiceUtil {
	private static final String filePath = "classpath*:bean/applicationContext.xml";
	public static ApplicationContext ctx;

	public static void setCtx(ApplicationContext webCtx) {
		ServiceUtil.ctx = webCtx;
	}
	/**
	 * 如果不是加载默认的applicationContext.xml,请先加载自定义文件,eg:"classpath*:bean/applicationContext-define.xml"
	 * @param filePath
	 */
	public static void setCtx(String filePath){
	    ApplicationContext context = null;
            try{
                PathMatchingResourcePatternResolver prp = new PathMatchingResourcePatternResolver();
                Resource[] platformResources = prp.getResources(filePath);
                if(platformResources.length>0){
                    context = new ClassPathXmlApplicationContext(platformResources[0].getURL().toString());   
                }                        
            }catch(Exception e){
                e.printStackTrace();
                context = null;
            }
	    ServiceUtil.ctx = context;
	}
	
	@SuppressWarnings("unchecked")
    public static <T> T getService(Class<T> businessInterface, String serviceName){
	    ApplicationContext ctx = getCtx();
	    if(ctx==null){
	        return null;
	    }
	    Object bean=null;
	    try{
	        bean = ctx.getBean(serviceName);
	    }catch (NoSuchBeanDefinitionException e){
	        return null;
	    }
	    return (T) bean;
	}
	
	public static ApplicationContext getCtx() {
	    if(ctx==null){
            try{
                PathMatchingResourcePatternResolver prp = new PathMatchingResourcePatternResolver();
                Resource[] platformResources = prp.getResources(filePath);
                if(platformResources.length>0){
                    ctx = new ClassPathXmlApplicationContext(platformResources[0].getURL().toString());   
                }                        
            }catch(Exception e){
                e.printStackTrace();
                ctx = null;
            }
        }
        return ctx;
	}
}
 

你可能感兴趣的:(spring容器)