java 绑定属性,Java属性文件绑定到Java接口

With GWT you have stuff like this:

public interface LoginConstants extends Constants {

@DefaultStringValue("Wellcome to my super app")

@Key("appDescription")

String appDescription();

@DefaultStringValue("Ok")

@Key("okButtonLabel")

String okButtonLabel();

}

Then you can use from your classes doing GWT.create(LoginConstant.class), in this way the interface is backed by dynamic implementation that, when I call loginConstants.appDescription() returns the value contained from a property file using the @Key annotation to reference the key in the property file. If the property file misses the property, then de @DefaultStringValue is returned. This is used for internationalization, but can possibly work also for configuration.

But with GWT, this is meant to be used on the client side (ie. translated to JavaScript), and for i18n, not for configuration.

But, I find this idea very convenient also for configuration handling.

I wonder if somebody knows a framework to do a similar thing on the server side, without necessarily bind your code to GWT. ie. if there is any library that implements this kind of logic specifically designed for the configuration handling. I am not aware of anything like this.

解决方案

I implemented my own solution to the question:

BASIC USAGE

The approach used by OWNER APIs, is to define a Java interface

associated to a properties file.

Suppose your properties file is defined as ServerConfig.properties:

port=80

hostname=foobar.com

maxThreads=100

To access this property you need to define a convenient Java interface

in ServerConfig.java:

public interface ServerConfig extends Config {

int port();

String hostname();

int maxThreads();

}

We'll call this interface the Properties Mapping Interface or just

Mapping Interface since its goal is to map Properties into an easy to

use a piece of code.

Then, you can use it from inside your code:

public class MyApp {

public static void main(String[] args) {

ServerConfig cfg = ConfigFactory.create(ServerConfig.class);

System.out.println("Server " + cfg.hostname() + ":" + cfg.port() +

" will run " + cfg.maxThreads());

}

}

But this is just the tip of the iceberg.

Continue reading here: Basic usage || Website || Github

I still have a couple of features in mind, but the current implementation goes a little forward than the basic functionalities described in the questions.

I need to add samples and documentation.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值