Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Registry optimization with Guice

  • Hi! Today I thought about a kind of optimization and have some questions...

Context : I'm developing in Java using Guice 2.


In my web application, I have a registry of converter to convert on the fly to a certain type. A converter is described as follows:

public class StringToBoolean implements Converter<String, Boolean>
{

  @Override
  public Boolean convert(String from) 
  {
      return Boolean.valueOf(from);
  }

}

My registry is none other than a Map:

public class ConverterRegistryImpl implements ConverterRegistry
{  

  private Map<Key,Converter<?,?>> converterRegistry = new HashMap<Key, Converter<?,?>>();

  @Override
  public <F, T> void register(Class<F> fromType, Class<T> toType, Converter<F, T> converter) 
  {
      converterRegistry.put(new Key(fromType,toType), converter);
  }

}

Finally I register my converter in my registry (class: ServletModule:configureServlets())
I think this step could be optimized...

ConverterRegistryImpl registry = new ConverterRegistryImpl();
registry.register(String.class, Integer.class, new StringToInteger());
registry.register(String.class, Boolean.class, new StringToBoolean());
...
//Then I bind the registry to this current instance...
bind(ConverterRegistry.class).toInstance(registry)

In this way I can use it everywhere like this :

@Inject 
ConverterRegistry converter;

  • Well I'm searching the best way to implement this using Guice.
  • More generally, how did you build that sort of registry with Guice (or without) ?

Thanks in advance !

like image 585
Jarod Avatar asked Feb 23 '26 00:02

Jarod


1 Answers

Don't know what exactly do you mean by "optimize". One of drawbacks of your approach is that you create your converters and registry by hand, so you do not use benefits of dependency injection for them. Also you can not accumulate converters from different modules.

This can be fixed with multibindings extension to guice: http://code.google.com/p/google-guice/wiki/Multibindings

    Injector injector = Guice.createInjector(new Module() {
        @Override
        public void configure(Binder binder) {
            @SuppressWarnings("rawtypes")
            Multibinder<Converter> converterBinder = Multibinder.newSetBinder(binder, Converter.class);
            converterBinder.addBinding().to(StringBooleanConverter.class);
            converterBinder.addBinding().to(BooleanStringConverter.class);
        }
    });
    ConverterRegistryImpl registry = injector.getInstance(ConverterRegistryImpl.class);

The full code is avaliable at: https://gist.github.com/1217563

like image 195
Ivan Sopov Avatar answered Feb 24 '26 13:02

Ivan Sopov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!