완료 후 샘플 응용 프로그램에서 dagger2를 시도했지만이 코드는 예외를 표시하고 있습니다.단검 2 : @Inject 생성자 또는 @ Provides-annotated 메서드를 사용하여 제공 할 수 없습니다.
번호 :
@Singleton
@Component(modules = {UserModule.class,BackendServiceModule.class})
public interface AppComponent {
BackendServiceModule provideBackendService();
// allow to inject into our Main class
// method name not important
void inject(MainActivity mainActivity);
}
public class AppGlobal extends Application
{
AppComponent appComponent;
public static AppGlobal global;
@Override
public void onCreate() {
super.onCreate();
global = this;
initAppComponent();
}
private void initAppComponent() {
}
public AppComponent getDataComponent() {
return appComponent;
}
}
public class BackendService {
@Inject
public User user;
private String serverUrl;
@Inject
public BackendService(@Named("serverUrl") String serverUrl) {
this.serverUrl = serverUrl;
}
public boolean callServer() {
if (user !=null && serverUrl!=null && serverUrl.length()>0) {
System.out.println("User: " + user + " ServerUrl: " + serverUrl);
return true;
}
return false;
}
}
@Module
public class BackendServiceModule
{
@Provides
@Singleton
BackendService provideBackendService(@Named("serverUrl") String serverUrl) {
return new BackendService(serverUrl);
}
@Provides
@Named("serverUrl")
String provideServerUrl() {
return "http://www.vogella.com";
}
@Provides
@Named("anotherUrl")
String provideAnotherUrl() {
return "http://www.google.com";
}
}
public class MainActivity extends AppCompatActivity {
@Inject
BackendService service;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AppGlobal.global.getDataComponent().inject(this);
TextView result = (TextView) findViewById(R.id.resulttxt);
result.setText(service.callServer()+"");
}
}
public class User {
private String firstName;
private String lastName;
public User(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
@Override
public String toString() {
return "User [firstName=" + firstName + ", lastName=" + lastName + "]";
}
@Module
public class UserModule
{
@Singleton
@Provides
User providesUser()
{
return new User("syam","jjjj");
}
}
예외 : 오류 (16, 26) 오류 : com.example.intrio.daggersample2.BackendServiceModule가 @Inject 생성자없이 또는 @로부터 제공 될 수는 애노테이션 제공 방법 . com.example.intrio.daggersample2.BackendServiceModule이 AppComponent
에서 com.example.intrio.daggersample2.AppComponent.provideBackendService()
이제 코드가 변경되었지만 여전히 작동합니다. 사용자 개체가 null입니다. – skyshine
@skyshine 모듈에서 'BackendService'생성자를 호출하면 Dagger에 당신은 당신 자신을 생성하고 있습니다; '@Inject' 필드를 설정하는 과정을 따라 가지 않습니다. Dagger가'@Inject' 생성자를 호출하고'@Inject' 필드를 설정할 수 있도록'@Provides BackendService' 메소드를 삭제하고 BackendService 클래스에'@ Singleton'을 넣으십시오. –