Files
mkdocs/docs/android面试/开源框架/Dagger2原理.md
2026-01-15 11:53:37 +08:00

3.0 KiB
Raw Blame History

Dagger2原理

目录


Dagger2原理

定义

// Dagger2依赖注入框架
// 编译时生成代码
// 类型安全
// 性能好

核心概念

// 1. Component组件注入器
// 2. Module模块提供依赖
// 3. Inject注入标记
// 4. Provides提供方法

依赖注入

依赖注入方式

// 1. 构造函数注入
public class UserRepository {
    private ApiService apiService;
    
    @Inject
    public UserRepository(ApiService apiService) {
        this.apiService = apiService;
    }
}

// 2. 字段注入
public class MainActivity extends AppCompatActivity {
    @Inject
    UserRepository userRepository;
}

// 3. 方法注入
@Inject
void setUserRepository(UserRepository userRepository) {
    this.userRepository = userRepository;
}

注解处理

注解类型

// @Inject标记需要注入的依赖
@Inject
UserRepository userRepository;

// @Module提供依赖的模块
@Module
public class AppModule {
    @Provides
    ApiService provideApiService() {
        return new ApiService();
    }
}

// @Component注入器
@Component(modules = {AppModule.class})
public interface AppComponent {
    void inject(MainActivity activity);
}

组件与模块

Module

@Module
public class AppModule {
    @Provides
    @Singleton
    ApiService provideApiService() {
        return new ApiService();
    }
}

Component

@Component(modules = {AppModule.class})
public interface AppComponent {
    void inject(MainActivity activity);
}

// 使用
AppComponent component = DaggerAppComponent.builder()
    .appModule(new AppModule())
    .build();
component.inject(this);

Dagger2源码分析

关键类

// Component组件接口
// Module模块类
// Inject注入注解
// DaggerXXX生成的组件实现

编译时生成

// 编译时生成 DaggerAppComponent
// 实现 AppComponent 接口
// 提供依赖注入逻辑

Dagger2最佳实践

1. 使用单例

@Provides
@Singleton
ApiService provideApiService() {
    return new ApiService();
}

2. 模块化设计

// 按功能划分模块
@Module
public class NetworkModule { }

@Module
public class DatabaseModule { }

面试常见问题

Q1: Dagger2 的原理?

答案:

  • 编译时生成代码
  • 实现依赖注入
  • 类型安全,性能好

Q2: Dagger2 和 Hilt 的区别?

答案:

  • Dagger2:基础框架,需要手动配置
  • HiltDagger2 的封装,更易用,官方推荐

Q3: 依赖注入的优势?

答案:

  1. 解耦:降低耦合度
  2. 测试:易于测试
  3. 复用:代码复用

最后更新2024年