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

196 lines
3.0 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Dagger2原理
## 目录
- [Dagger2原理](#dagger2原理)
- [依赖注入](#依赖注入)
- [注解处理](#注解处理)
- [组件与模块](#组件与模块)
- [Dagger2源码分析](#dagger2源码分析)
- [Dagger2最佳实践](#dagger2最佳实践)
- [面试常见问题](#面试常见问题)
---
## Dagger2原理
### 定义
```java
// Dagger2依赖注入框架
// 编译时生成代码
// 类型安全
// 性能好
```
### 核心概念
```java
// 1. Component组件注入器
// 2. Module模块提供依赖
// 3. Inject注入标记
// 4. Provides提供方法
```
---
## 依赖注入
### 依赖注入方式
```java
// 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;
}
```
---
## 注解处理
### 注解类型
```java
// @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
```java
@Module
public class AppModule {
@Provides
@Singleton
ApiService provideApiService() {
return new ApiService();
}
}
```
### Component
```java
@Component(modules = {AppModule.class})
public interface AppComponent {
void inject(MainActivity activity);
}
// 使用
AppComponent component = DaggerAppComponent.builder()
.appModule(new AppModule())
.build();
component.inject(this);
```
---
## Dagger2源码分析
### 关键类
```java
// Component组件接口
// Module模块类
// Inject注入注解
// DaggerXXX生成的组件实现
```
### 编译时生成
```java
// 编译时生成 DaggerAppComponent
// 实现 AppComponent 接口
// 提供依赖注入逻辑
```
---
## Dagger2最佳实践
### 1. 使用单例
```java
@Provides
@Singleton
ApiService provideApiService() {
return new ApiService();
}
```
### 2. 模块化设计
```java
// 按功能划分模块
@Module
public class NetworkModule { }
@Module
public class DatabaseModule { }
```
---
## 面试常见问题
### Q1: Dagger2 的原理?
**答案:**
- 编译时生成代码
- 实现依赖注入
- 类型安全,性能好
### Q2: Dagger2 和 Hilt 的区别?
**答案:**
- **Dagger2**:基础框架,需要手动配置
- **Hilt**Dagger2 的封装,更易用,官方推荐
### Q3: 依赖注入的优势?
**答案:**
1. 解耦:降低耦合度
2. 测试:易于测试
3. 复用:代码复用
---
*最后更新2024年*