问题
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.)
回答1:
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.
来源:https://stackoverflow.com/questions/14622549/how-to-make-a-class-configurable-without-adding-any-code