`
trent_luo
  • 浏览: 43677 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

创建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;
	}
}
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics