1

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).

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.)

einpoklum
  • 118,144
  • 57
  • 340
  • 684
  • Off topic, but I'm just curious; The constructor to A takes a string argument. Why would you want to configure that? If class B creates A it needs to give in a title. Why would you want to override that value with configuration? That would certainly not be what class B expects (that the title changes). – Halvard Jan 31 '13 at 09:58
  • I don't want to configure that, that's why I marked it as `@unconfigurable`... – einpoklum Jan 31 '13 at 11:53
  • True enough, but inside the constructor you still have `configure(title);` (which is commented out, but indicates that you want it to be run behind the scenes). Nevermind, I see that in principle we agree. Sorry I can't answer your main question ... – Halvard Feb 04 '13 at 08:14

1 Answers1

0

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) { ... }

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

Erik Pragt
  • 13,513
  • 11
  • 58
  • 64