【问题标题】:Guice - How to use binding annotations to build a list of objectsGuice - 如何使用绑定注释来构建对象列表
【发布时间】:2012-11-01 19:32:52
【问题描述】:

我创建了 Guice 绑定注释,允许我根据注释绑定一个类的两个不同实例,例如:

bind(Animal.class).withAnnotation(Cat.class).toInstance(new Animal("Meow"));
bind(Animal.class).withAnnotation(Dog.class).toInstance(new Animal("Woof"));

我希望能够创建一个提供者方法,该方法提供一个列表,该列表是我的一个类的依赖项,但不知道如何为此使用注释:

@Provider
List<Animal> provideAnimalList() {
    List<Animal> animals = new ArrayList<Animal>();
    animals.add(@Cat Animal.class); // No, but this is what I want
    animals.add(@Dog Animal.class); // No, but this is what I want
    return animals;
}

所以我假设我只能使用 List 的 add() 方法的参数中的注释......但是没有。

我应该如何处理这个问题?在我看来,简单地new Animal 类的两个实例会更简单,也许这不是绑定注释的使用方式。

感谢 cmets 在这种情况下最好地使用绑定注释。

谢谢

【问题讨论】:

    标签: dependency-injection guice


    【解决方案1】:

    如果它真的是你想要的,这里有一个可行的解决方案:

    public class AnimalModule extends AbstractModule {
        @Override
        protected void configure() {
            bind(Animal.class).annotatedWith(Cat.class).toInstance(new Animal("Meow"));
            bind(Animal.class).annotatedWith(Dog.class).toInstance(new Animal("Woof"));
        }
    
        @Provides
        List<Animal> provideAnimalList(@Cat Animal cat, @Dog Animal dog) {
            List<Animal> animals = new ArrayList<Animal>();
            animals.add(cat);
            animals.add(dog);
            return animals;
        }
    
        public static void main(String[] args) {
            List<Animal> animals = Guice.createInjector(new AnimalModule()).getInstance(Key.get(new TypeLiteral<List<Animal>>() {
            }));
            for (Animal animal : animals) {
                System.out.println(animal);
            }
        }
    }
    

    注释:

    @Retention(value = RetentionPolicy.RUNTIME)
    @BindingAnnotation
    public @interface Cat {
    }
    

    输出:

    Animal{sound='Meow'}
    Animal{sound='Woof'}
    

    然而

    • 不要创建特定的注释,在这种情况下似乎没有必要。请改用@Named
    • 你可以考虑Multibindings来解决这个问题。

    【讨论】:

    • +1 用于多重绑定,这看起来是解决此问题的正确解决方案(易于扩展)。
    • 来自文档:由于编译器无法检查字符串,我们建议谨慎使用@Named
    猜你喜欢
    • 2016-08-06
    • 2018-04-25
    • 1970-01-01
    • 2012-10-16
    • 2012-10-20
    • 2016-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多