首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >理解用于Android开发的Dagger 2

理解用于Android开发的Dagger 2
EN

Stack Overflow用户
提问于 2015-08-28 17:28:09
回答 2查看 1.3K关注 0票数 0

这是我的代码,我是根据互联网上的一些老教程编写的。在Dagger 2的主站点上应该有一些例子,我发现很难理解如何实现这一切。

要想运行这么简单的应用程序,实在是太费劲了。我有两个问题:

我是否必须在每个类中调用DaggerLoggerComponent,以获得像我的Logger类这样的组件?

另外,如何使Logger类的作用域成为单例?现在,每个按钮单击创建一个新的记录器实例。

也许我不理解一些基本的概念,我以前只在Spring中使用过依赖注入,这一切对我来说都很奇怪。

代码语言:javascript
复制
public class MainActivity extends AppCompatActivity {

    private Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }

    private void init(){
        button = (Button)findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LoggerComponent component = DaggerLoggerComponent.builder().loggerModule(new LoggerModule()).build();
                component.getLogger().log("Hello!",MainActivity.this);
            }
        });
    }

}


public class Logger {

    private static int i = 0;

    public Logger(){
        i++;
    }

    public static int getI() {
        return i;
    }

    public void log(String text, Context context){
        Toast.makeText(context,text+" "+i,Toast.LENGTH_SHORT).show();
    }
}


@Singleton
@Component(modules={LoggerModule.class})
public interface LoggerComponent {

    Logger getLogger();

}


@Module
public class LoggerModule {
    @Provides
    @Singleton
    Logger provideLogger(){
        return new Logger();
    }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-08-28 22:24:59

答案是

代码语言:javascript
复制
public class MainActivity extends AppCompatActivity {
    @OnClick(R.id.button) //ButterKnife
    public void onClickButton() {
        logger.log("Hello!");
    }

    @Inject
    Logger logger;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Injector.INSTANCE.getApplicationComponent().inject(this);
        ButterKnife.bind(this);
    }

    @Override
    protected void onDestroy() {
        ButterKnife.unbind(this);
        super.onDestroy();
    }
}

public class Logger {
    private static int i = 0;

    private CustomApplication customApplication;

    public Logger(CustomApplication application) {
        this.customApplication = application;
        i++;
    }

    public static int getI() {
        return i;
    }

    public void log(String text){
        Toast.makeText(customApplication, text + " " + i,Toast.LENGTH_SHORT).show();
    }
}


public interface LoggerComponent {
    Logger logger();
}

@Module
public class ApplicationModule {
    private CustomApplication customApplication;

    public ApplicationModule(CustomApplication customApplication) {
        this.customApplication = customApplication;
    }

    @Provides
    public CustomApplication customApplication() {
        return customApplication;
    }
}

@Module
public class LoggerModule {
    @Provides
    @Singleton
    Logger provideLogger(){
        return new Logger();
    }
}


@Singleton
@Component(modules={LoggerModule.class, ApplicationModule.class})
public interface ApplicationComponent extends LoggerComponent {
    CustomApplication customApplication();

    void inject(MainActivity mainActivity);
}

public class CustomApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        Injector.INSTANCE.initializeApplicationComponent(this);
    }
}

public enum Injector {
    INSTANCE;

    private ApplicationComponent applicationComponent;

    public ApplicationComponent getApplicationComponent() {
        return applicationComponent;
    }

    void initializeApplicationComponent(CustomApplication customApplication) {
        this.applicationComponent = DaggerApplicationComponent.builder()
            .applicationModule(new ApplicationModule(customApplication))
            .build();
    }
}

This is currently our Dagger2 architecture.

编辑:这是来自我们正在制作的应用程序中的Retrofit内容的实际代码:

代码语言:javascript
复制
public interface RecordingService {    
    ScheduledRecordsXML getScheduledRecords(long userId)
            throws ServerErrorException;
}

public class RecordingServiceImpl
        implements RecordingService {

    private static final String TAG = RecordingServiceImpl.class.getSimpleName();

    private RetrofitRecordingService retrofitRecordingService;

    public RecordingServiceImpl(RetrofitRecordingService retrofitRecordingService) {
        this.retrofitRecordingService = retrofitRecordingService;
    }

    @Override
    public ScheduledRecordsXML getScheduledRecords(long userId)
            throws ServerErrorException {
        try {
            return retrofitRecordingService.getScheduledPrograms(String.valueOf(userId));
        } catch(RetrofitError retrofitError) {
            Log.e(TAG, "Error occurred in downloading XML file.", retrofitError);
            throw new ServerErrorException(retrofitError);
        }
    }
}

@Module
public class NetworkClientModule {
    @Provides
    @Singleton
    public OkHttpClient okHttpClient() {
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.interceptors().add(new HeaderInterceptor());
        return okHttpClient;
    }
}

@Module(includes = {NetworkClientModule.class})
public class ServiceModule {
    @Provides
    @Singleton
    public RecordingService recordingService(OkHttpClient okHttpClient, Persister persister, AppConfig appConfig) {
        return new RecordingServiceImpl(
                new RestAdapter.Builder().setEndpoint(appConfig.getServerEndpoint())
                        .setConverter(new SimpleXMLConverter(persister))
                        .setClient(new OkClient(okHttpClient))
                        .setLogLevel(RestAdapter.LogLevel.NONE)
                        .build()
                        .create(RetrofitRecordingService.class));
    }

    //...
}

public interface RetrofitRecordingService {
    @GET("/getScheduledPrograms")
    ScheduledRecordsXML getScheduledPrograms(@Query("UserID") String userId);
}

public interface ServiceComponent {
    RecordingService RecordingService();

    //...
}

public interface AppDomainComponent
        extends InteractorComponent, ServiceComponent, ManagerComponent, ParserComponent {
}

@Singleton
@Component(modules = {
        //...
        InteractorModule.class,
        ManagerModule.class,
        ServiceModule.class,
        ParserModule.class
    //...
})
public interface ApplicationComponent
        extends AppContextComponent, AppDataComponent, AppDomainComponent, AppUtilsComponent, AppPresentationComponent {
    void inject(DashboardActivity dashboardActivity);
    //...
}
票数 2
EN

Stack Overflow用户

发布于 2015-08-28 19:10:19

我是否必须在每个类中调用DaggerLoggerComponent,以获得像我的Logger类这样的组件?

是的,对于系统创建的所有类,如应用程序、活动和服务。但对于你自己的课程来说,你不需要这个。只要用@inject注释构造函数,dagger就会提供依赖关系。

另外,如何使Logger类的作用域成为单例?现在,每个按钮单击创建一个新的记录器实例。

你的独生子女设置是正确的。但是您必须在创建活动(onCreate)之后一次初始化组件,以便让匕首注入所有字段。此外,如果您不需要立即使用Logger对象,则可以使用惰性注入功能。

代码语言:javascript
复制
    @Inject
    Logger logger;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        LoggerComponent component = DaggerLoggerComponent.builder().loggerModule(new LoggerModule()).build();

        component.inject(this);

        init();
    }

然后,您可以访问您的对象,而无需从组件获取引用:

代码语言:javascript
复制
private void init(){
        button = (Button)findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                logger.log("Hello!",MainActivity.this);
            }
        });
    }

总之:您必须在所有使用字段注入的类中初始化组件。

更新:要执行实际的注入,必须在组件中声明inject()方法,dagger将自动实现它。此方法将负责提供任何带有@Inject注解的对象。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32276639

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档