0

我想我錯過了一些東西。我得到這個錯誤:匕首:爲什麼匕首需要一個@inject構造函數來實現一個不依賴於另一個對象的對象

PostsVM cannot be provided without an @Inject constructor or from an 
@Provides-annotated method. 

假設類如下:

@Module 
public class AppModule { 
    private final Application mApplication; 

    @Singleton 
    @Provides 
    ViewModel provideListViewModel() { 
     return new PostsVM(); 
    } 
} 

和A類PostVM

@Singleton 
public class PostsVM extends ViewModel { 

    public boolean get(){ 
     return true; 
    } 
} 

和部件:

@Singleton 
@Component(modules = AppModule.class) 
public interface AppComponent { 

    void inject(Global global); 

    void inject(MainActivity mainActivity); 

    @Architecture.ApplicationContext 
    Context getContext(); 

    Application getApplication(); 
} 

和在活動:

@Inject 
public   ViewModelProvider.Factory factory; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    InjectorClass.inject(this); 

正如你所看到的,對於PostVM類給出的例子,簡化版,取決於什麼,爲什麼需要它的@Inject構造函數?

回答

2

tl; dr爲了防止錯誤並遵循約定。


@Inject的JavaDoc你可以閱讀:

Injectable constructors are annotated with @Inject and accept zero or more dependencies as arguments. @Inject can apply to at most one constructor per class.

它總是很好的做法,按照慣例/文檔。


所以@Inject標誌着一個切入點匕首,以表示它在何處以及如何創建類。這是您打算如何使用班級的明確標誌。

  • 如果你有多個構造函數呢?
  • 如果您需要其他設置並且應該使用@Module而不是?

通過只是默認爲一個無參數的構造函數(如果可能)事情可以開始打破很容易,你可能不能夠很容易地查明來源,如果你只是假設匕首,它的工作。

__ cannot be provided without an @Inject constructor or from an @Provides-annotated method. 

另一方面,這個錯誤給了你一個強烈的信號,表明你錯過了一些東西,不能被忽略。

+0

好吧,我現在得到這個部分,所以@Inject既是需要依賴項的類,也是提供依賴項的類? – Relm

+0

@Relm'@Inject'在你想創建的類的構造函數上,並且你想要注入的字段 –