---
title: "试用配置管理库typesafe.config"
author: "wbj0110"
date: "2015-03-10T10:38:46Z"
tags: ["akka"]
categories: ["编程语言"]
slug: "typesafe-config"
draft: false
lastmod: "2016-03-12T13:20:08Z"
id: 2187423
url: "https://soledede.iteye.com/blog/2187423"
---

## 试用配置管理库typesafe.config

Typesafe的Config库，纯Java写成、零外部依赖、代码精简、功能灵活、API友好。支持Java properties、JSON、JSON超集格式HOCON以及环境变量。它也是Akka的配置管理库.

### []()Overview

- 纯java实现，无任何依赖
- 充分的测试
- 支持: Java properties, JSON, and a human-friendly JSON superset
- 可以合并各种格式的配置文件
- 可以通过文件、urls、classpath加载配置
- 支持多层嵌套的配置方式
- 识别Java system properties, 如`java -Dmyapp.foo.bar=10`
- 可以转换长短，大小等单位。如配置文件中`timeout=10s`,则可以转换成任意的毫秒或者
- 类型转换，比如yes可以转换为boolean类型的true
- JSON superset features:
  
  - comments
  - includes
  - substitutions `("foo" : ${bar}`, `"foo" : Hello ${who})`
  - properties-like notation (a.b=c)
  - less noisy, more lenient syntax
  - substitute environment variables (logdir=${HOME}/logs)

目前config只支持配置文件，如果想从数据库获取配置文件，需要自己diy。 config库很擅长合并配置。

### []()Example

默认加载classpath下的application.conf,application.json和application.properties文件。通过ConfigFactory.load()加载。

```
# these are our own config values defined by the app
simple-app {
    answer=42
}

# Here we override some values used by a library
simple-lib.foo="This value comes from simple-app's application.conf"
simple-lib.whatever = "This value comes from simple-app's application.conf"
```

```
public class SimpleLibContext {
    private Config config;

    //指定配置文件
    public SimpleLibContext(Config config) {
        this.config = config;
        config.checkValid(ConfigFactory.defaultReference(), "simple-lib");
    }

    // 默认加载classpath下的application.*
    public SimpleLibContext() {
        this(ConfigFactory.load());
    }

    //打印
    public void printSetting(String path) {
        System.out.println("The setting '" + path + "' is: " + config.getString(path));
    }

    public static void main(String[] args) {
        SimpleLibContext s = new SimpleLibContext();
        s.printSetting("simple-app.answer");
    }
}
```

### []()Reference

[http://stackoverflow.com/questions/18668883/using-typesafes-config-to-manage-my-database-connection](http://stackoverflow.com/questions/18668883/using-typesafes-config-to-manage-my-database-connection)  
[https://github.com/typesafehub/config/tree/master/examples](https://github.com/typesafehub/config/tree/master/examples)  
[https://github.com/typesafehub/config](https://github.com/typesafehub/config)