我最近遇到一些代码,它使用同一方法上的@Provides
和@Inject
注解。该方法有两个非原始参数和一个非void返回类型。合并@Provides和@Inject
我想知道是否合理使用这两个串联。从我可以收集/推测的内容来看,似乎使用@Inject
来构建使用Guice的方法依赖关系,而使用@Provides
来绑定返回类型。任何想法,将不胜感激。
我最近遇到一些代码,它使用同一方法上的@Provides
和@Inject
注解。该方法有两个非原始参数和一个非void返回类型。合并@Provides和@Inject
我想知道是否合理使用这两个串联。从我可以收集/推测的内容来看,似乎使用@Inject
来构建使用Guice的方法依赖关系,而使用@Provides
来绑定返回类型。任何想法,将不胜感激。
不,不会有这种情况,您可以用同样的方法看到@Provides
和@Inject
。
@Inject
使得上构造函数,方法和字段感:
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
方法。
非常感谢您的澄清。因此,为了清楚起见,用@Inject注解的方法在构造YourInjectableClass之后调用,然后调用? – OrangeApple3
@ OrangeApple3是的。该技术被称为[方法注入](https://github.com/google/guice/wiki/Injections#method-injection)。 –