OWNER支持配置文件目录的继承

什么是OWNER

OWNER 是一个开源项目,旨在解决Java配置文件的解析问题。

例如配置文件 /data/config.properties 包含下列内容:

server.port=80
server.hostname=foobar.com
server.max.threads=100

为了解析这个配置文件,我们首先定义一个Java接口:

import org.aeonbits.owner.Config;

@Sources({ //定义配置文件的路径
     "file:/data/config.properties",
     "classpath: config.properties" 
})    
public interface ServerConfig extends Config {
    @Key("server.port")
    int port();

    @Key("server.hostname")
    String hostname();

    @Key("server.max.threads");
    @DefaultValue("42")
    int maxThreads();
}

加载配置文件:

ServerConfig cfg = ConfigFactory.create(ServerConfig.class);
System.out.println("Server " + cfg.hostname() + ":" + cfg.port() +
                   " will run " + cfg.maxThreads());

配置文件路径的继承

在实际应用中,配置文件内容上一般会包括多个分组,每一个分组定义成一个接口会更加清晰,同时所有的接口需要从相同的配置文件列表中加载。例如除了上面例子中展示的server配置以外,还要定义mysql的信息,就需要添加一个接口并重新定义Sources :

import org.aeonbits.owner.Config;

@Sources({ //定义配置文件的路径
     "file:/data/config.properties",
     "classpath: config.properties" 
})    
public interface MysqlConfig extends Config {
    @Key("mysql.port")
    int port();

    @Key("mysql.hostname")
    String hostname();
}

由于Sources这个annonation不支持继承,所以每次新添加一组配置项的时候就需要重写一遍Sources,这样一来容易出错并且以后修改配置文件路径的时候多有不便。我提交了一个patch解决了这个问题,已经merge到master,针对这种情况就可以这样写了:

import org.aeonbits.owner.Config;

@Sources({ //定义配置文件的路径
     "file:/data/config.properties",
     "classpath: config.properties" 
})    
public interface BaseConfig extends Config {
    
}
import org.aeonbits.owner.Config;

public interface ServerConfig extends BaseConfig {
    @Key("server.port")
    int port();

    @Key("server.hostname")
    String hostname();

    @Key("server.max.threads");
    @DefaultValue("42")
    int maxThreads();
}
import org.aeonbits.owner.Config;

public interface MysqlConfig extends BaseConfig {
    @Key("mysql.port")
    int port();

    @Key("mysql.hostname")
    String hostname();
}

转载于:https://my.oschina.net/u/575122/blog/836850

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值