【问题标题】:How to make a class configurable without adding any code?如何在不添加任何代码的情况下使类可配置?
【发布时间】:2013-01-31 09:37:15
【问题描述】:

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

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);
        }
    }
}

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

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

【问题讨论】:

  • 离题,但我只是好奇; A 的构造函数接受一个字符串参数。为什么要配置它?如果 B 类创建 A,它需要给出一个标题。为什么要使用配置覆盖该值?这肯定不是 B 类所期望的(标题发生了变化)。
  • 我不想配置它,所以我将它标记为@unconfigurable...
  • 确实如此,但在构造函数内部仍然有configure(title);(已被注释掉,但表明您希望它在幕后运行)。没关系,我认为原则上我们同意。抱歉,我无法回答您的主要问题...

标签: java configuration annotations libraries


【解决方案1】:

你可以做的是使用 Spring 3.0 EL。可以找到一个示例here,但它基本上归结为您可以执行以下操作:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-07
    • 1970-01-01
    • 2021-06-08
    • 2014-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多