使用Guice进行注册表优化 [英] Registry optimization with Guice

查看:165
本文介绍了使用Guice进行注册表优化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  • 嗨!
    今天我想到了一种优化并有一些问题......

上下文:
我正在使用Guice 2开发Java。

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

在我的Web应用程序中,我有一个转换器注册表,可以动态转换为某种类型。转换器描述如下:

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);
  }

}






最后我在我的注册表中注册我的转换器(类:ServletModule:configureServlets())

我认为这一步可以优化...

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;







  • 我好吗?我正在寻找使用Guice实现这一目标的最佳方法。

  • 更一般地说,你是如何使用Guice(或不使用)构建那种注册表的?

  • 提前致谢!

    推荐答案

    不知道到底是什么意思是优化。您的方法的一个缺点是您手动创建转换器和注册表,因此您不会使用依赖注入的好处。此外,你不能累积来自不同模块的转换器。

    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.

    这可以通过multibindings扩展到guice修复: http://code.google.com/p/google-guice/wiki/Multibindings

    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);
    

    完整代码可在以下网址找到: https://gist.github.com/1217563

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

    这篇关于使用Guice进行注册表优化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆