Registry optimization with Guice

我怕爱的太早我们不能终老 提交于 2019-12-07 13:20:13

问题


  • 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 !


回答1:


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



来源:https://stackoverflow.com/questions/7420900/registry-optimization-with-guice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!