作者:张量扰动艹_712 | 来源:互联网 | 2023-05-16 20:09
我正在尝试编译https://github.com/svenjacobs/android-dagger2-example
但我遇到了与未作用域组件相关的错误,具体取决于作用域组件.(Android Studio 1.1,Gradle 2.2.1).此外,如果有人知道其他Dagger2 Android示例与FRAGMENTS我想知道他们.
更新:这是另一个非常基本的片段示例:https:
//github.com/gk5885/dagger-android-sample
/Users/Mac1/android-dagger2-example-master/app/src/main/java/com/svenjacobs/dagger2/ActivityComponent.java
Error:(15, 1) error: com.svenjacobs.dagger2.ActivityComponent (unscoped) cannot depend on scoped components:
@Singleton com.svenjacobs.dagger2.ApplicationComponent
Error:Execution failed for task ':app:compileDebugJava'.
> Compilation failed; see the compiler error output for details.
这是文件ActivityComponent,显然没有作用域:
import dagger.Component;
/**
* Component for all activities.
*
* @author Sven Jacobs
*/
@Component(dependencies = ApplicationComponent.class,
modules = {
MainActivityModule.class,
AModule.class,
BModule.class
})
interface ActivityComponent extends AFragment.Injector, BFragment.Injector {
void inject(MainActivity activity);
void inject(AnotherActivity activity);
}
这是范围组件:
package com.svenjacobs.dagger2;
import javax.inject.Singleton;
import dagger.Component;
/**
* Application-wide dependencies.
*
* @author Sven Jacobs
*/
@Singleton
@Component(modules = ApplicationModule.class)
interface ApplicationComponent {
void inject(Dagger2Application application);
/**
* Provides dependency for sub-components
*/
SomeApplicationDependency someApplicationDependency();
}
Adam Mcnabb..
14
您需要为ApplicationComponent提供范围.这不一定是@Singleton,因为Dagger 2允许您使用界面上的@Qualifier注释定义自己的范围.
@Scope
public @interface CustomScopeName {
}
然后你可以像这样使用它:
@CustomScopeName
@Component(dependencies = ApplicationComponent.class,
modules = {
MainActivityModule.class,
AModule.class,
BModule.class
}) .......
我认为不允许在未作用域组件中使用作用域依赖项的原因是为了防止Singletons依赖非Singleton对象并防止循环依赖.
1> Adam Mcnabb..:
您需要为ApplicationComponent提供范围.这不一定是@Singleton,因为Dagger 2允许您使用界面上的@Qualifier注释定义自己的范围.
@Scope
public @interface CustomScopeName {
}
然后你可以像这样使用它:
@CustomScopeName
@Component(dependencies = ApplicationComponent.class,
modules = {
MainActivityModule.class,
AModule.class,
BModule.class
}) .......
我认为不允许在未作用域组件中使用作用域依赖项的原因是为了防止Singletons依赖非Singleton对象并防止循环依赖.