Web项目中Spring配置文件外置

目标:加载任意路径下的Spring配置文件到WebApplicationContex

实现:

1.新建一个类ConfigurationMnager,用于读取用户目录下的配置文件config.properties。如:C:\Document And Setting\Harden\config.properties。代码如下:

package com.harden.util;

import java.util.Properties;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class ConfigurationManager {
	private static Properties propertie;
	private static FileInputStream inputFile;
	
	public static String getConfig(String key)
    {
		propertie = new Properties();
        try {
        	String configPath = "/config.properties";
        	if(System.getProperty("os.name").contains("Windows"))
        		configPath = "\\config.properties";
            inputFile = new FileInputStream(System.getProperty("user.home")+configPath);
            propertie.load(inputFile);
            inputFile.close();
        } catch (FileNotFoundException ex) {
            System.out.println("读取属性文件失败");
            ex.printStackTrace();
        } catch (IOException ex) {
            System.out.println("装载文件失败!");
            ex.printStackTrace();
        }
        if(propertie.containsKey(key)){
            String value = propertie.getProperty(key);//得到某一属性的值
            return value;
        }
        else 
            return "";
    }
		
}


2.新建一servlet名为LoadXMLBeansServlet,代码如下。config.properties文件中有一属性BEANS_XML,指向要加载的Spring配置文件路径,如: BEANS_XML=C:\\applicantionContext.xml:

package com.harden.servlet;

import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.PropertyConfigurator;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.xml.ResourceEntityResolver;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.web.context.ConfigurableWebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.harden.util.ConfigurationManager;

/**
 * Servlet implementation class LoadXMLBeansServlet
 */
public class LoadXMLBeansServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoadXMLBeansServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Servlet#init(ServletConfig)
	 */
	public void init(ServletConfig config) throws ServletException {
		System.out.println("in load xml");
                super.init(config);
		loadBeansFromXML(config,ConfigurationManager.getConfig("BEANS_XML"));	
		
	}
	
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		loadBeansFromXML(this.getServletConfig(),ConfigurationManager.getConfig("BEANS_XML"));
	}

	/**
	 * @see Servlet#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}
	
	private void loadBeansFromXML(ServletConfig config,String XMLPath){
		ConfigurableWebApplicationContext wac = (ConfigurableWebApplicationContext) WebApplicationContextUtils.getRequiredWebApplicationContext(config.getServletContext());
		XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader((BeanDefinitionRegistry)wac.getBeanFactory());   
		reader.setResourceLoader(wac);   
		reader.setEntityResolver(new ResourceEntityResolver(wac));   
        try {   
            String[] configLocations = new String[]{XMLPath};   
            for(int i=0;i<configLocations.length;i++){   
            	reader.loadBeanDefinitions(wac.getResources(configLocations[i]));
            }   
        } catch (BeansException e) {   
            e.printStackTrace();   
        } catch (IOException e) {   
            e.printStackTrace();   
        }		
	}
}

3.在web.xml中配置LoadXMLBeansServlet启动

<servlet>
    <description></description>
    <display-name>LoadXMLBeansServlet</display-name>
    <servlet-name>LoadXMLBeansServlet</servlet-name>
    <servlet-class>com.harden.servlet.LoadXMLBeansServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>LoadXMLBeansServlet</servlet-name>
    <url-pattern>/LoadXMLBeansServlet</url-pattern>
  </servlet-mapping>


4.至此,当服务器(Tomcat)启动时,就会读取外置配置文件如:C:\applicantionContext.xml,将其中定义的bean加载到Spring的WebApplicantionContext中。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值