Question

Context

I want to automatically inject configuration items using Guice. My configuration framework is typesafe's config.

public class MyObject {
  @Configuration("value") int value;
}

To do that, I wrote an annotation.

// Annotations skipped, but correct
public @interface Configuration {
  String value();
}

And I wrote a module. This module checks for all types to inject, then allows the injection itself.

public class ConfigurationModule extends AbstractModule {
  @Override protected void configure() {
    final Config config = ConfigFactory.load();
    class ConfigurationMembersInjector<T> implements MembersInjector<T> {
      private final Field field;
      ConfigurationMembersInjector(Field field) {
        this.field = field;
        field.setAccessible(true);
      }
      @Override public void injectMembers(T t) {
        try {
          String key = field.getAnnotation(Configuration.class).value();
          field.set(t, config.getXxxx()); // what to write?
        } catch (IllegalAccessException e) {
          throw new RuntimeException(e);
        }
      }
    }
    class ConfigurationTypeListener implements TypeListener {
      @Override public <T> void hear(TypeLiteral<T> typeLiteral, TypeEncounter<T> typeEncounter) {
        for (Field field : typeLiteral.getRawType().getDeclaredFields()) {
          if (field.isAnnotationPresent(Configuration.class)) {
            typeEncounter.register(new ConfigurationMembersInjector<T>(field));
          }
        }
      }
    }
    bindListener(Matchers.any(), new ConfigurationTypeListener());
  }
}

Question

How do I automatically convert a configuration item to a specific yet unknown type? Is there a way to say "I want this item converted as this type"? Also, is there a way to "register" custom converters?

Or else, do I have to write my own conversion mechanism?

Was it helpful?

Solution 2

Since version 1.3.0 (released on April 16th, 2015), there exists a ConfigBeanFactory, which is the closest thing to what I ask. A bit late for my project but happens to do the trick.

OTHER TIPS

Another alternative to what you're trying to do is to use a Classpath scanner to scan for your custom annotation (which I assume is a Binding Annotation) and then bind your configuration values to those types annotated with those annotations.

This is the exact approach I take in developing my library: Typesafe Config Guice, which binds config values from a Typesafe Config file to annotated parameters and fields.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top