java - Google Guice - 如何自动添加绑定(bind)

标签 java guice

在我的项目中,我使用 Google Guice用于依赖注入(inject)。在扩展 Google Guice 的 AbstactModule 的 Module 类中,我有一个 MapBinder,其中键是项目的名称,值是我的 Item 接口(interface)的实现(例如 FirstItem)。

MapBinder<String, Item> itemMapBinder = MapBinder.newMapBinder(binder(), String.class, Item.class);
itemMapBinder.addBinding("FirstItem").to(FirstItem.class);

目前,每次我添加项目的新实现(例如 SecondItem)时,我还必须向模块添加新行,例如

itemMapBinder.addBinding("SecondItem").to(SecondItem.class);

我正在我的 ItemFactory 中使用此项目 map 。

public class ItemFactoryImpl implements ItemFactory {

    private final Map<String, Item> items;

    @Inject
    public ItemFactoryImpl(Map<String, Item> items) {
        this.items = items;
    }

    @Override
    public Item getItem(String name) {
        if (name == null) throw new IllegalArgumentException("Name cannot be null");
        return items.get(name);
    }
}

我试图找到一种方法来自动为 Item 接口(interface)的新实现添加绑定(bind)。我的想法是使用自定义注释,该注释将添加到 Item 接口(interface)的新实现中,并以某种方式修改 Module#configure 以使用此自定义注释为所有类添加绑定(bind)。我完成了这样的事情:

// cz.milanhlinak.guiceautobinding.item.AutoBindableItem.java
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface AutoBindableItem {
}

// cz.milanhlinak.guiceautobinding.item.Item.java
public interface Item {
}

// cz.milanhlinak.guiceautobinding.item.SecondItem.java
@AutoBindableItem
public class SecondItem implements Item {
}

// cz.milanhlinak.guiceautobinding.Module.java
public class Module extends AbstractModule {

    @Override
    protected void configure() {

        MapBinder<String, Item> itemMapBinder = MapBinder.newMapBinder(binder(), String.class, Item.class);
        new Reflections("cz.milanhlinak.guiceautobinding.item")
            .getTypesAnnotatedWith(AutoBindableItem.class)
            .stream()
            .filter(Item.class::isAssignableFrom)
            .forEach(typeAnnotatedWith -> itemMapBinder
                    .addBinding(typeAnnotatedWith.getSimpleName())
                    .to((Class<? extends Item>) typeAnnotatedWith)
            );

        bind(ItemFactory.class).to(ItemFactoryImpl.class).in(Singleton.class);
    }
}

完整代码可以在我的 GitHub repository 中找到.

我想知道是否有更好的方法来实现与Google Guice的自动绑定(bind),因为正如你所看到的,我目前正在使用一个额外的库 - Reflections .

更新

另一个选项可能是使用 Google Guava而不是Reflections

public class Module extends AbstractModule {

    @Override
    protected void configure() {

        MapBinder<String, Item> itemMapBinder = MapBinder.newMapBinder(binder(), String.class, Item.class);

        ClassPath classPath;
        try {
            classPath = ClassPath.from(Thread.currentThread().getContextClassLoader());
        } catch (IOException e) {
            throw new RuntimeException("Unable to read class path resources", e);
        }

        ImmutableSet<ClassPath.ClassInfo> topLevelClasses = classPath.getTopLevelClassesRecursive("cz.milanhlinak.guiceautobinding.item");
        topLevelClasses.stream()
                .map(ClassPath.ClassInfo::load)
                .filter(clazz -> clazz.isAnnotationPresent(AutoBindableItem.class) && Item.class.isAssignableFrom(clazz))
                .forEach(clazz -> itemMapBinder
                        .addBinding(clazz.getSimpleName())
                        .to((Class<? extends Item>) clazz));

        bind(ItemFactory.class).to(ItemFactoryImpl.class).in(Singleton.class);
    }
}

最佳答案

你没有做错任何事。

使用反射没有任何问题。该工具非常出色,可以完成您想要的工作。

Guice 没有发现工具,因此没有“默认”方式可以仅在 Guice 中执行您想要的操作。

如果你想使用 Reflections 之外的其他东西,你可以依靠 java.util.ServiceLoader,但是 ServiceLoader 并不是真正适合 Guice 的,因为它会自动创建实例,但您通常使用 Guice 是因为您希望它为您创建实例,而不是让另一个框架为您创建实例。

使用 Guava 的 Classpath 的替代方案也很有意义,但 Reflections 更强大,因为您还可以加载不在类路径中的类。

底线,您已经做出了更好的选择。

关于java - Google Guice - 如何自动添加绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52915611/

相关文章:

java - 无论我做什么,DividerItemDecoration 都不起作用

java - 使用 Dagger 2 的自定义注解拦截器

java - 来自 Guice 的 "Please wait until after injection has completed to use this object"错误

java - 使用 Guice 和 "Law of Demeter"进行依赖注入(inject)

java - 数学题: how to know if coordinate is in 'row' ?

java - jetty worker 。使用dockerfile创建镜像时出错

java - 以长类型存储 session 值

java - 吐出文本,将其添加到表格中

scala - 如何在 Scala/SBT 中安装 Guice?

tomcat - guice 的问题