json 作为配置文件

来源:互联网 发布:linux修改snmp团体名 编辑:程序博客网 时间:2024/05/21 19:32
从以前的 xml 到现在的 properties ,配置方式都很 suck 。我今天发现,既然有 gson 这样的利用反射的 json parser ,何不用 json 呢?

下面是 Config 类,用来保存配置:(使用了 commons-io 2.1 、gson 2.1)

import java.io.FileInputStream;
import java.io.IOException;
import org.apache.commons.io.IOUtils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

public class Config {
        String listen_port;
        String hdfs;

        private static Config _instance;

        static {
                Gson gson = new Gson();
                FileInputStream configIn = null;
                try {
                        configIn = new FileInputStream("hdfs.conf.json");
                        _instance = gson.fromJson(IOUtils.toString(configIn), Config.class);
                } catch (JsonSyntaxException e) {
                        e.printStackTrace();
                } catch (IOException e) {
                        e.printStackTrace();
                } finally {
                        IOUtils.closeQuietly(configIn);
                }
        }

        public static Config getInstance() {
                return _instance;
        }
}

下面是配置文件 hdfs.conf.json :

{
        listen_port: "8080",
        hdfs: "hdfs://192.168.3.233:54310"
}

Gson 在解析 json 的时候使用了反射,所以写出来的代码很简洁。要添加更多的配置属性,只需在类定义里面添加 field ,然后对应的 json 添加相应的项目就行了,其他代码不需要做任何改动。
0 0
原创粉丝点击