Spring加载自定义配置文件内容

本文介绍了一个基于Spring框架的RESTful Bean配置实例及其实现细节,包括XML配置文件的解析、Bean实现类的编写及其核心方法的运作流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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

二:Bean实现类如下:

public class RestfulBean implements Restful {

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

    private String root;
    private Map<String,String> businessMap;
    protected ZkClient zkClient;

    public String getRoot() {
        return root;
    }

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

    public Map<String, String> getBusinessMap() {
        return businessMap;
    }

    public void setBusinessMap(Map<String, String> 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<String> getRestUrls(String businessKey) {
        try{
            List<String> children = zkClient.getChildren(ZKPaths.makePath(root, businessKey));
            return Lists.transform(children, new Function<String, String>() {
                @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<String> restUrls = getRestUrls(businessKey);
            if (restUrls != null&&restUrls.size()>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

### 如何在 Spring Boot 中指定自定义配置文件位置 在 Spring Boot 应用程序中,可以通过多种方式来指定自定义配置文件的位置。以下是几种常见的方式: #### 使用命令行参数 可以在启动应用程序时通过命令行参数传递配置文件的位置。例如: ```bash java -jar myapp.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties,file:./config/application.properties ``` 这会告诉 Spring Boot 从多个位置加载配置文件,并按照顺序覆盖相同的属性[^1]。 #### 修改 `application.properties` 或 `application.yml` 也可以直接在 `application.properties` 或者 `application.yml` 文件里指明其他外部配置文件的位置: 对于 properties 文件来说: ```properties spring.config.additional-location=file:///path/to/config/ ``` 而对于 yml 文件则是这样写: ```yaml spring: config: additional-location: file:///path/to/config/ ``` 这种方式允许开发者灵活地添加额外的配置源而无需改变原有的配置文件结构[^3]。 #### 利用环境变量 还可以利用操作系统的环境变量来设定配置文件路径,在 Linux/Unix 系统上可以这样做: ```bash export SPRING_CONFIG_LOCATION=/path/to/config/ ``` 而在 Windows 上则应使用 set 命令代替 export 。之后再运行 jar 包即可自动识别该目录下的配置文件[^2]。 以上方法均能有效地帮助用户更改默认情况下位于 classpath 下的应用程序配置文件的位置,从而满足不同场景下对资源配置的需求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值