2017-06-17 61 views
1

我最近遇到一些代码,它使用同一方法上的@Provides@Inject注解。该方法有两个非原始参数和一个非void返回类型。合并@Provides和@Inject

我想知道是否合理使用这两个串联。从我可以收集/推测的内容来看,似乎使用@Inject来构建使用Guice的方法依赖关系,而使用@Provides来绑定返回类型。任何想法,将不胜感激。

回答

6

不,不会有这种情况,您可以用同样的方法看到@Provides@Inject

@Inject使得上构造函数,方法和字段感:

  • 在构造函数,它标志着该DI框架应该调用构造函数。该框架提供了所有参数值。
  • 在字段上,它表示DI框架应该从外部设置字段。该框架提供了字段值。
  • 在方法上,它表明在构建之后,DI框架应该调用方法,恰好一次是。该框架提供参数值。返回值没有意义,通常为void

例如:

public class YourInjectableClass { 

    // Guice will use this constructor... 
    @Inject public YourInjectableClass(YourDep dep) { /* ... */ } 
    // ...instead of this one 
    public YourInjectableClass(YourDep dep, YourOtherDep otherDep) { /* ... */ } 

    // Guice will populate this field after construction. 
    @Inject YourField yourField; 

    @Inject public void register(Registry registry) { 
    // Guice will create or get a Registry and call this method after construction. 
    // It sometimes makes sense for this to be protected or package-private, 
    // so this class's consumers aren't tempted to call it themselves. 
    } 
} 

@Provides具有窄得多的目的:当在吉斯模块中使用,@Provides推移方法和指示吉斯应该调用该方法时,它需要该方法的一个实例可能 - 参数化类型(并从方法本身继承绑定注释或限定符)。 Dagger具有类似的注释,因为@Provides未在JSR-330依赖注入标准中定义。

public class YourModule extends AbstractModule { 
    @Override public void configure() {) // still needed for AbstractModule 

    // Guice will call this whenever it needs a @SomeBindingAnnotation YourInstance. 
    // Because you list a YourDep as a parameter, Guice will get and pass in a YourDep. 
    @Provides @SomeBindingAnnotation YourInstance create(YourDep dep) { 
    return YourInstanceFactory.create(dep); 
    } 
} 

因此,你应该几乎从来没有看到这些标注在同一个文件,更不用说在同一个方法。唯一的例外是,如果您遵循可疑的做法来制作一个本身可注入的模块(假设从一个注入器获取注入的模块以配置不同的注入器),即使如此,也不会以相同的方法看到它们: @Inject方法被调用一次以存储依赖关系,并且每当需要新实例时应调用@Provides方法。

+0

非常感谢您的澄清。因此,为了清楚起见,用@Inject注解的方法在构造YourInjectableClass之后调用,然后调用? – OrangeApple3

+0

@ OrangeApple3是的。该技术被称为[方法注入](https://github.com/google/guice/wiki/Injections#method-injection)。 –