如何在不添加任何代码的情况下使类可配置? [英] How to make a class configurable without adding any code?

查看:25
本文介绍了如何在不添加任何代码的情况下使类可配置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够(用 Java)编写如下内容:

I would like to be able to write (in Java) something like the following:

public class A implements MagicallyConfigurable {

    @configuration_source_type{"xml"}
    @configuration_dir{"some/rel/path/"}

    /* or maybe some other annotations specifying a db-based configuration etc. */

    int length = 4 /* some kind of default */;
    char c = '*' /* some kind of default */;

    @do_not_configure
    String title;

    A(String title) {

        /* possibly, but hopefully no need to, something like:
        configure();
        call here. */

        this.title = title;
    }

    void goForIt() {
        System.out.println(title);
        for(int i=0; i < length; i++) {
            System.out.print(c);
        }
    }
}

并让它按预期工作.也就是说,我唯一需要根据配置初始化字段的事情就是添加一些注释、实现一个接口并可能进行单个函数调用(但希望没有它).

and for it to work as expected. That is, the only thing I would need to initialize fields based on a configuration would be adding some annotations, implementing an interface and possibly making a single function call (but hopefully without it).

我确信这在理论上是可行的,问题是是否有一个现有的库/框架/附加组件/东西可以启用它.(也许 Apache commons.configuration 不知何故?以前没有使用过它.)

I'm sure this is theoretically doable, the question is whether there's an existing library/framework/add-on/thingie which enables it. (Maybe Apache commons.configuration somehow? Haven't worked with it before.)

推荐答案

你能做的,就是使用 Spring 3.0 EL.一个例子可以在这里找到,但它是什么基本上归结为您可以执行以下操作:

What you can do, is to use Spring 3.0 EL. An example can be found here, but what it basically boils down to is that you can do the following:

@Value("#{systemProperties.databaseName}")
public void setDatabaseName(String dbName) { ... }

您的属性将被自动设置.这将适用于 setter 和属性.

And your properties will be automatically set. This will work on setters and on properties.

这篇关于如何在不添加任何代码的情况下使类可配置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆