- 加载策略 properties 文件和映射接口的关联是通过 owner API 匹配类名和文件名(.properties)来实现的,当然这个逻辑是可以根通过一些额外的注解来实现用户个性化的需求。
- 引用属性 你可以使用另外的机制来加载属性到映射接口中,那就是在调用 ConfigFactory.create() 时人工指定一个属性对象:
- 参数化属性 owner 另外一个杰出的特性,就是它允许在方法接口上提供参数。属性值应当遵循 java.util.Formatter 类指定的位置计数规则。
- 类型转换 owner API 支持原始类型和枚举类型的属性转换。当你定义映射接口时,你可以使用广泛的返回类型,并且他们会自动从 String 类型转换成原始类型或者枚举类型。
这也是开发 owner 的宗旨。
owner是个功能丰富的 API,但在增加更多的功能之前,我们尽可能的保持它现有基本用法的简单化。
owner API 支持一系列功能,如下:
- 加载策略
- 引用属性
- 参数化属性
- 类型转换
- 变量扩展
- 加载和热加载
- 可访问性和可变性
- 程序调试
- 禁用功能
- 配置工厂
- XML支持
- 事件支持
- 单例
新特性的开发不希望将已有特性变得复杂,版本的向后兼容也在我们的目标当中。
加载策略 properties 文件和映射接口的关联是通过 owner API 匹配类名和文件名(.properties)来实现的,当然这个逻辑是可以根通过一些额外的注解来实现用户个性化的需求。
@Sources({ "file:~/.myapp.config",
"file:/etc/myapp.config",
"classpath:foo/bar/baz.properties" })
public interface ServerConfig extends Config {
@Key("server.http.port")
int port();
@Key("server.host.name")
String hostname();
@Key("server.max.threads");
@DefaultValue("42")
int maxThreads();
}
在上面的例子中, owner 会尝试从不同的 @Sources 中加载属性:
- 首先,它会尝试从用户home目录的 ~/.myapp.config 加载属性文件,假如找到,这个文件将会被使用;
- 假如上一个失败,它就会尝试从 /etc/myapp.config 加载属性文件,假如找到,这个文件将会被使用;
- 作为最后的手段,它将尝试从类路径下以 foo/bar/baz.properties 标志的文件中加载属性;
- 假如以上 URL 资源都不存在,java 类将不会与任何文件相关联,只有 @DefaultValue 会被使用。假如没有默认值,将会返回null(就像 java.util.Properties)
在上面的例子中,属性值只会从第一个被找到的文件中加载。一旦有匹配的文件被加载,其他的都会被忽略。这是使用了 @Sources 注解的默认加载方式,你也可以显式的在接口定义时使用 @LoadPolicy(LoadType.FIRST) 注解来指定。
那么假如你需要在一些属性间做一些重载该怎么办?没问题,这完全是可能的,你可以通过 @LoadPolicy(LoadType.MERGE) 注解来实现:
@LoadPolicy(LoadType.MERGE)
@Sources({ "file:~/.myapp.config",
"file:/etc/myapp.config",
"classpath:foo/bar/baz.properties" })
public interface ServerConfig extends Config {
...
}
}
这种情况下,所有 URL 中指定的文件都将被查询到,并且第一个定义某重载属性的文件中的值将会被采纳。具体过程如下:
- 首先,它会从 ~/.myapp.config 中加载指定的属性,如果找到就将关联的属性值返回;
- 然后,从 /etc/myapp.config 中加载指定的属性,如果找到就将关联的属性值返回;
- 最后它会从 classpath 路径下的 foo/bar/baz.properties 中加载指定的属性,如果找到就将关联的属性值返回;
- 假如指定的属性未在上述任何文件中找到的话,它就会返回用 @DefaultValue 标注的值,否则返回null。
因此基本上我们在多个 properties 文件中执行合并,且第一个properties 文件会重写后面的文件的相同属性值。
@Sources注解通过语法 file:${user.home}/.myapp.config (通过’user.home’ 系统属性得到解决)或者 file:${HOME}/.myapp.config (通过$HOME 环境变量得到解决)考虑系统属性或环境变量。前面例子中使用的“~”是另一个变量扩展的例子,它等同于 ${user.home}。
引用属性 你可以使用另外的机制来加载属性到映射接口中,那就是在调用 ConfigFactory.create() 时人工指定一个属性对象:
public interface ImportConfig extends Config {
@DefaultValue("apple")
String foo();
@DefaultValue("pear")
String bar();
@DefaultValue("orange")
String baz();
}
// 然后...
Properties props = new Properties();
props.setProperty("foo", "pineapple");
props.setProperty("bar", "lime");
ImportConfig cfg = ConfigFactory.create(ImportConfig.class, props); // 属性引用!
assertEquals("pineapple", cfg.foo());
assertEquals("lime", cfg.bar());
assertEquals("orange", cfg.baz());
当然你可以同时指定多个需要引用的属性:
ImportConfig cfg = ConfigFactory.create(ImportConfig.class, props1, props2, ...);
假如 props1 和 props2 同时指定了同一个属性的值,那么首先指定的值将会被采用。
Properties p1 = new Properties();
p1.setProperty("foo", "pineapple");
p1.setProperty("bar", "lime");
Properties p2 = new Properties();
p2.setProperty("bar", "grapefruit");
p2.setProperty("baz", "blackberry");
ImportConfig cfg = ConfigFactory.create(ImportConfig.class, p1, p2); // 属性引用!
assertEquals("pineapple", cfg.foo());
// p1先指定,所以这是 lime 而不是 grapefruit
assertEquals("lime", cfg.bar());
assertEquals("blackberry", cfg.baz());
此外,你可以非常方便的引用系统属性或环境变量:
interface SystemEnvProperties extends Config {
@Key("file.separator")
String fileSeparator();
@Key("java.home")
String javaHome();
@Key("HOME")
String home();
@Key("USER")
String user();
void list(PrintStream out);
}
SystemEnvProperties cfg = ConfigFactory.create(SystemEnvProperties.class, System.getProperties(), System.getenv());
assertEquals(File.separator, cfg.fileSeparator());
assertEquals(System.getProperty("java.home"), cfg.javaHome());
assertEquals(System.getenv().get("HOME"), cfg.home());
assertEquals(System.getenv().get("USER"), cfg.user());
与加载策略的交互 上面讲到的“引用属性”是属性加载机制中的附加功能。通过代码引入的属性在优先级上要高于通过 @Sources 注释的方式。假设有这样一个场景,你已通过 @Sources 定义你的配置文件,但是你又想让用户在代码中自己指定配置文件,这个时候怎么办呢?
@Sources(...)
interface MyConfig extends Config {
...
}
public static void main(String[] args) {
MyConfig cfg;
if (args.lenght() > 0) {
Properties props = new Properties();
props.load(new FileInputStream(new File(args[0])));
cfg = ConfigFactory.create(MyConfig.class, userProps);
} else {
cfg = ConfigFactory.create(MyConfig.class);
}
}
在上例中,用户指定的 properties 文件将会重写通过 @Sources 注解加载的 properties 文件中的同名属性。很多命令行工具会使用这种方式,它允许用户在命令行中重写默认配置。(这仅针对1.0.3.1及更高级的版本,在1.0.3.1版本之前引用属性优先级比从 properties 文件中加载的要低。这在1.0.3.1作出改变,并将在以后的版本中都采用这种方式)
参数化属性 owner 另外一个杰出的特性,就是它允许在方法接口上提供参数。属性值应当遵循 java.util.Formatter 类指定的位置计数规则。
public interface Sample extends Config {
@DefaultValue("Hello Mr. %s!")
String helloMr(String name);
}
Sample cfg = ConfigFactory.create(Sample.class);
print(cfg.helloMr("Luigi")); // will println 'Hello Mr. Luigi!'
禁用参数扩展 owner 支持用户关闭参数扩展,这可以通过使用 @DisableFeature 注解来实现。
public interface Sample extends Config {
@DisableFeature(PARAMETER_FORMATTING)
@DefaultValue("Hello %s.")
public String hello(String name);
// 将会忽略参数并返回"Hello %s."
}
@DisableFeature 注解可以用在方法层面,也可以用在接口层面,当使用在接口层面时,将会适用于该接口下的所有方法。
DisableFeature(PARAMETER_FORMATTING)
public interface Sample extends Config {
@DefaultValue("Hello %s.")
public String hello(String name);
// 将会忽略参数并返回"Hello %s."
}
类型转换 owner API 支持原始类型和枚举类型的属性转换。当你定义映射接口时,你可以使用广泛的返回类型,并且他们会自动从 String 类型转换成原始类型或者枚举类型。
// conversion happens from the value specified in the properties files (if available).
int maxThreads();
// conversion happens also from @DefaultValue
@DefaultValue("3.1415")
double pi();
// enum values are case sensitive! java.util.concurrent.TimeUnit is an enum
@DefaultValue("NANOSECONDS");
TimeUnit timeUnit();
你可以在配置接口中将业务对象定义为返回类型,甚至是你自定义的对象,最简单的方式就是使用一个带 String 参数的 public 构造参数来定义你的业务对象:
public class CustomType {
private final String text;
public CustomType(String text) {
this.text = text;
}
public String getText() {
return text;
}
}
public interface SpecialTypes extends Config {
@DefaultValue("foobar.txt")
File sampleFile();
@DefaultValue("http://owner.aeonbits.org")
URL sampleURL();
@DefaultValue("example")
CustomType customType();
@DefaultValue("Hello %s!")
CustomType salutation(String name);
}
owner API 会将”example”传递给 CustomType 的构造函数并返回。
数组和集合
owner 具有对 java 数组和集合的第一级支持,因此你可以这样定义属性:
public class MyConfig extends Config {
@DefaultValue("apple, pear, orange")
public String[] fruit();
@Separator(";")
@DefaultValue("0; 1; 1; 2; 3; 5; 8; 13; 21; 34; 55")
public int[] fibonacci();
@DefaultValue("1, 2, 3, 4")
List<Integer> ints();
@DefaultValue("http://aeonbits.org, http://github.com, http://google.com")
MyOwnCollection<URL> myBookmarks();
// Concrete class are allowed (in this case java.util.Stack)
// when type is not specified <String> is assumed as default
@DefaultValue("The Lord of the Rings,The Little Prince,The Da Vinci Code")
Stack books();
}
你可以通过对接口明确指定 Collection、 List、 Set、 SortedSet 或者 Vector、 Stack、 LinkedList 等具体实现(甚至你自己实现的 java 集合框架接口,只要在实现类中定义一个默认无参的构造函数)来使用数组对象、原始类型或者 java 集合(但是要注意,并不支持 Map 接口及其子接口)。
默认情况下 woner 使用逗号(”,”)来分割数组和集合中的元素,但是你可以通过 @Separator 注解来指定不同的字符。假如你的属性有更复杂的拆分逻辑,你可以通过 @TokenizerClass 注解加上 Tokenizer 接口来自定义断词器类。例如:
public class MyConfig extends Config {
@Separator(";")
@DefaultValue("0; 1; 1; 2; 3; 5; 8; 13; 21; 34; 55")
public int[] fibonacci();
@TokenizerClass(CustomDashTokenizer.class)
@DefaultValue("foo-bar-baz")
public String[] withSeparatorClass();
}
public class CustomDashTokenizer implements Tokenizer {
// this logic can be as much complex as you need
@Override
public String[] tokens(String values) {
return values.split("-", -1);
}
}
@Separator 和 @TokenizerClass 能够作用在方法层面和接口层面,当只在方法层面指定时只对该方法有效,当在接口层面上指定时则对整个接口类生效。方法层面上指定的注解会覆盖类层面上的注解:
@Separator(";")
public interface ArrayExample extends Config {
// takes the class level @Separator
@DefaultValue("1; 2; 3; 4")
public int[] semicolonSeparated();
// overrides the class-level @Separator(";")
@Separator(",")
@DefaultValue("1, 2, 3, 4")
public int[] commaSeparated();
// overrides the class level @Separator(";")
@TokenizerClass(CustomDashTokenizer.class)
@DefaultValue("1-2-3-4")
public int[] dashSeparated();
}
需要注意的是,不能在同一级别上同时使用 @Separator 和 @TokenizerClass,因为这两个注解实际上是在干同一件事!比如下面的例子将会抛出 UnsupportedOperationException 异常:
// @Separator and @TokenizerClass cannot be used together
// on class level.
@TokenizerClass(CustomCommaTokenizer.class)
@Separator(",")
public interface Wrong extends Config {
// will throw UnsupportedOperationException!
@DefaultValue("1, 2, 3, 4")
public int[] commaSeparated();
}
public interface AlsoWrong extends Config {
// will throw UnsupportedOperationException!
// @Separator and @TokenizerClass cannot be
// used together on method level.
@Separator(";")
@TokenizerClass(CustomDashTokenizer.class)
@DefaultValue("0; 1; 1; 2; 3; 5; 8; 13; 21; 34; 55")
public int[] conflictingAnnotationsOnMethodLevel();
}
然而,即使在类层面上有冲突,woner 却能够在方法层面上进行纠正:
// @Separator and @TokenizerClass cannot be used together on class level.
@Separator(";")
@TokenizerClass(CustomDashTokenizer.class)
public interface WrongButItWorks extends Config {
// but this overrides the class level annotations
// hence it will work!
@Separator(";")
@DefaultValue("1, 2, 3, 4")
public int[] commaSeparated();
}
当然,我们是不建议这么做的,毕竟这是一种错误的设置方法(可以理解为 owner 自身的 bug 吧)……
@ConverterClass 注解
owner 通过提供 @ConverterClass 注解,使用户可以通过实现 Converter 接口指定自定义的转换逻辑。
interface MyConfig extends Config {
@DefaultValue("foobar.com:8080")
@ConverterClass(ServerConverter.class)
Server server();
@DefaultValue("google.com, yahoo.com:8080, owner.aeonbits.org:4000")
@ConverterClass(ServerConverter.class)
Server[] servers();
}
class Server {
private final String name;
private final Integer port;
public Server(String name, Integer port) {
this.name = name;
this.port = port;
}
}
public class ServerConverter implements Converter<Server> {
public Server convert(Method targetMethod, String text) {
String[] split = text.split(":", -1);
String name = split[0];
Integer port = 80;
if (split.length >= 2)
port = Integer.valueOf(split[1]);
return new Server(name, port);
}
}
MyConfig cfg = ConfigFactory.create(MyConfig.class);
Server s = cfg.server(); // will return a single server
Server[] ss = cfg.servers(); // it works also with collections
在上面的例子中,我们调用 servers() 并返回一个 Server 对象数组,ServerConverter 会被调用多次以转换每一个元素,并且在任何情况下 ServerConverter 都将针对单个元素工作。