If you have a ton of settings and want to avoid creating a new anchor annotation for each of them, you can try to put them in an enumeration and use this enumeration in a general anchor annotation. This may be a bit of a difficult decision, but it can also save a pattern that you are trying to avoid.
This way you can match object references (IDE-friendly) instead of strings (slow and fragile) and create only one anchor annotation.
public enum Config { DB_NAME("db_name"), DB_HOST("db_host_name_specified_in_file"), SOME_NUMBER("some_number"), ; private final String propertyName; private Config(String propertyName) { this.propertyName = propertyName; } public String getPropertyName() { return propertyName; } public InjectConfig annotation() { // Create an implementation of InjectConfig for ease of binding. return new InjectConfig() { @Override public Class<? extends Annotation> annotationType() { return InjectConfig.class; } @Override public Config value() { return Config.this; } @Override public boolean equals(Object obj) { if (obj == this) { return true; } else if (!(obj instanceof InjectConfig)) { return false; } return value() == ((InjectConfig) obj).value(); } /** @see Annotation
Now you can iterate and bind each in a loop:
public class YourModule extend AbstractModule { @Override public void configure() {
And enter only what you need directly:
YourClass(@InjectConfig(DB_USER) String user, @InjectConfig(SOME_NUMBER) int number) { }
I did not have the opportunity to verify this, but as far as I know, it should work. Given your specific usage settings, you may need to massage GetValueFromSettingsProvider , which you are writing, or write an override method getConfigValueFromSettings in the listing. Remember, however, that somehow you still need to store the tuple (key name, property name in the file, property type), and it seems that Enum is the best way to manage this programmatically.
source share