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;
Thanks in advance !
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With