如何在方法中注入依赖项?

how can I inject a dependency in a method?

我是依赖注入的初学者..特别是 Dagger 2。我想弄清楚if/how我可以做这样的事情:

@Inject
public void someMethodName(int someInteger, SomeObject dependency){
 // do something with the dependency. 
}

或者我是否需要将该依赖项作为 class var 放入?对此的任何帮助将不胜感激。同样在这种情况下,变量 someInteger 不是依赖项,而是由调用者添加的……这有关系吗?

我可以这样称呼它吗:

this.someMethodName(5); 

android工作室不喜欢上面的调用方式(我假设是因为我做错了)

您可以使用一些界面

public interface myDependence{
   int myFunction(int value);
}

现在在你身上实施 CLASS

public myClass implements MyDependence{
   @Override
   int myFunction(int value){
       // do something
   }
}
  1. 您需要创建由@Component 注解的组件。
  2. 组件接受提供依赖项的模块。
  3. 您创建的每个组件的名称都以 Dagger 前缀开头,例如对于 MyComponent。

让我们看下面的例子:

    @Singleton
    @Component(modules = DemoApplicationModule.class)
    public interface ApplicationComponent {
        void inject(DemoApplication application);
    }

我们使用单注入方法创建了ApplicationComponent。我们的意思是我们想在 DemoApplication 中注入某些依赖项。

此外,在 @Component 注释中,我们指定了带有提供方法的模块。

这就像我们的模块看起来像:

@Module
public class DemoApplicationModule {
   private final Application application;

   public DemoApplicationModule(Application application) {
       this.application = application;
    }

  @Provides @Singleton SomeIntegerHandler provideIntegerHandler() {
       return new MySomeIntegerHandlerImpl();
  }
 }

我们通过创建 DemoApplicationModule 的意思是,该模块可以在我们的组件指定的注入位置提供所需的依赖项。

 public class DemoApplication extends Application {
   private ApplicationComponent applicationComponent;

   @Inject SomeIntegerHandler handler;

   @Override public void onCreate() {
     super.onCreate();
     applicationComponent = DaggerApplicationComponent.builder()
         .demoApplicationModule(new DemoApplicationModule(this))
         .build();
     applicationComponent.inject(this);
     handler.someMethodName(5);
   }
  }

查看文档您可以获得哪些依赖项。除了仅获取原始实例之外,您还可以获得 Provider, Factory or Lazy 实例。 http://google.github.io/dagger/api/latest/dagger/Component.html

你也可以创建scoped dependencis,它的生命周期取决于注入地方的生命周期,比如Activities or Fragments

希望我向您介绍了 Dagger 是什么的基本概念。