---
title: "Spring加载自定义配置文件内容"
author: "xiaowei2002"
date: "2015-08-20T16:01:23Z"
tags: []
categories: ["企业架构"]
slug: "spring"
draft: false
lastmod: "2015-08-20T16:01:23Z"
id: 2236862
url: "https://xiaowei2002.iteye.com/blog/2236862"
---

一：bean的XML配置文件如下：

&lt;?xml version="1.0" encoding="UTF-8"?&gt;  
&lt;beans xmlns="[http://www.springframework.org/schema/beans](http://www.springframework.org/schema/beans)"  
       xmlns:xsi="[http://www.w3.org/2001/XMLSchema-instance](http://www.w3.org/2001/XMLSchema-instance)"  
       xsi:schemaLocation="[http://www.springframework.org/schema/beans](http://www.springframework.org/schema/beans) [http://www.springframework.org/schema/beans/spring-beans.xsd](http://www.springframework.org/schema/beans/spring-beans.xsd)"&gt;  
    &lt;bean id="restfulBean" class="com.hyxt.restful.registry.RestfulBean" init-method="start"&gt;  
        &lt;property name="zkClient" ref="zkClient"/&gt;  
        &lt;property name="root" value="restfulCommand"/&gt;  
        &lt;property name="businessMap"&gt;  
            &lt;map&gt;  
                &lt;!--&lt;entry key="cashCommand" value="[http://{server}:8082/posRequest/forPosApi/posMutual"/](http://%7Bserver%7D:8082/posRequest/forPosApi/posMutual%22/)&gt;  
             &lt;entry key="cashCommand1" value="[http://{server}:8080/demoPrj/rest/demo1"/](http://%7Bserver%7D:8080/demoPrj/rest/demo1%22/)&gt;  
              &lt;entry key="cashCommand2" value="[http://{server}:8080/demoPrj/rest/demo2"/](http://%7Bserver%7D:8080/demoPrj/rest/demo2%22/)&gt;--&gt;  
            &lt;/map&gt;  
        &lt;/property&gt;  
    &lt;/bean&gt;  
    &lt;!-- 引入zookeeper client bean --&gt;  
    &lt;import resource="zookeeper.xml"/&gt;  
&lt;/beans&gt;

二：Bean实现类如下:

public class RestfulBean implements Restful {

    private Logger logger = LoggerFactory.getLogger(RestfulBean.class);

    private String root;  
    private Map&lt;String,String&gt; businessMap;  
    protected ZkClient zkClient;

    public String getRoot() {  
        return root;  
    }

    public void setRoot(String root) {  
        this.root = root;  
    }

    public Map&lt;String, String&gt; getBusinessMap() {  
        return businessMap;  
    }

    public void setBusinessMap(Map&lt;String, String&gt; businessMap) {  
        this.businessMap = businessMap;  
    }

    public ZkClient getZkClient() {  
        return zkClient;  
    }

    public void setZkClient(ZkClient zkClient) {  
        this.zkClient = zkClient;  
    }

    public void start() {  
        if(root==null||"".equals(root)){  
            throw new RuntimeException("没有定义根节点");  
        }  
        if(businessMap==null){  
            throw new RuntimeException("没有定义restful服务");  
        }

        try {  
            for (String businessKey : businessMap.keySet()){  
                String url = businessMap.get(businessKey);  
                url = url.replace("{server}", NetUtils.getLocalHost());  
                url = URLEncoder.encode(url, "UTF-8");  
                String path = ZKPaths.makePath(root, businessKey, url);  
                //不管有没有，先删除掉再开始发布  
                try{  
                    zkClient.deletePath(path);  
                }catch (Exception e){  
                    ;  
                }  
                zkClient.createPath(path, CreateMode.EPHEMERAL);  
                logger.info("发布reftful服务\[{}]: {} 成功",businessKey,url);  
            }  
        } catch (Exception e) {  
            throw new RuntimeException(e.getMessage(),e);  
        }  
    }

    @Override  
    public List&lt;String&gt; getRestUrls(String businessKey) {  
        try{  
            List&lt;String&gt; children = zkClient.getChildren(ZKPaths.makePath(root, businessKey));  
            return Lists.transform(children, new Function&lt;String, String&gt;() {  
                @Override  
                public String apply(String s) {  
                    try {  
                        return URLDecoder.decode(s, "UTF-8");  
                    } catch (UnsupportedEncodingException e) {  
                        throw new RuntimeException(e.getMessage(), e);  
                    }  
                }  
            });  
        }catch (Exception e){  
            logger.error(e.getMessage(),e);  
            return null;  
        }  
    }

    @Override  
    public String getRestUrl(String businessKey) {  
        try{  
            List&lt;String&gt; restUrls = getRestUrls(businessKey);  
            if (restUrls != null&&restUrls.size()&gt;0) {  
                return restUrls.get(new Random().nextInt(restUrls.size()));  
            }  
        }catch (Exception e){  
            logger.error(e.getMessage(),e);  
        }  
        return null;  
    }

    @Override  
    public void listener(final String businessKey, final RestfulListener listener) {  
        try{  
            zkClient.pathListener(ZKPaths.makePath(root, businessKey), new PathChildrenCacheListener() {  
                @Override  
                public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {  
                    listener.childChange(businessKey);  
                }  
            });  
        }catch (Exception e){  
            logger.error(e.getMessage(),e);  
        }  
    }

}

三：初始化时加载配置文件,如test.xml