【问题标题】:Dynamically bind instances using guice使用 guice 动态绑定实例
【发布时间】:2014-04-22 16:32:13
【问题描述】:

在我的应用程序(独立的 apache camel)中,我必须绑定几个 bean(pojos 的实例)。 因为这些pojos不能直接使用(在java中),但必须通过url中的绑定引用来使用,所以我想在一个枚举中“注册”所有可用的bean。然后像这样绑定 bean:

public class BeanRegistry extends JndiRegistry {
    public BeanRegistry() {
        for (Beans bean : Beans.values()) {
            try {
                this.bind(bean.name(), bean.clazz().newInstance());
            } catch (InstantiationException | IllegalAccessException e) {
                throw new IllegalStateException("Problem on instantiating bean " + bean.name() + " with type "
                                                + bean.clazz().getName() + ", cause Exception: ", e);
            }
        }

    }


    public static enum Beans {
        sorter(SortingStrategy.class),
        policy(PolicyForStartAndStopRoutes.class),
        doneFilter(ExcludeDoneFilesFilter.class);

        private final Class<?> clazz;

        Beans(Class<?> clazz) {
            this.clazz = clazz;
        }

        public Class<?> clazz() {
            return clazz;
        }
    }
}

只要您使用枚举的名称来引用 bean,就不会发生拼写错误。 我的问题是bean.clazz().newInstance()。有没有办法使用 guice 来“提供”实例?使用 guice,我可以将实例绑定到任意构造函数或“实现”。

【问题讨论】:

    标签: dependency-injection guice


    【解决方案1】:

    我找到了使用MapBinder 的解决方案。它被打包在一个单独的依赖项中:

    <dependency>
        <groupId>com.google.inject.extensions</groupId>
        <artifactId>guice-multibindings</artifactId>
        <version>3.0</version>
    </dependency>
    

    这是我的新代码(它显示了我的 guice 模块)它与我的另一个 question 相关:

    @Override
    protected final void configure() {
        ....
        // bind beans to instances
        MapBinder<String, Object> boundBeans = MapBinder.newMapBinder(binder(), String.class, Object.class);
        for (Beans bean : Beans.values()) {
            boundBeans.addBinding(bean.name()).to(bean.clazz());
        }
    }
    
    /**
     *
     * @param boundBeans all beans bound via a {@link MapBinder}
     * @return a jndi registry with all beans (from {@link Beans}) bound 
     */
    @Provides
    @Inject
    final Registry getRegistry(final Map<String, Object> boundBeans) {
        JndiRegistry registry = new JndiRegistry();
        for (Entry<String, Object> boundBean : boundBeans.entrySet()) {
            registry.bind(boundBean.getKey(), boundBean.getValue());
        }
        return registry;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-14
      相关资源
      最近更新 更多