具有Hilt的Android上的依赖注入

重点 (Top highlight)

Dependency injection (DI) is a technique widely used in programming and well suited to Android development, where dependencies are provided to a class instead of creating them itself. By following DI principles, you lay the groundwork for good app architecture, greater code reusability, and ease of testing. Have you ever tried manual dependency injection in your app? Even with many of the existing dependency injection libraries today, it requires a lot of boilerplate code as your project becomes larger, since you have to construct every class and its dependencies by hand, and create containers to reuse and manage dependencies.

依赖项注入 (DI)是一种广泛用于编程的技术,非常适合Android开发,该类将依赖项提供给类,而不是自己创建依赖项。 通过遵循DI原则,您将为良好的应用程序体系结构,更高的代码可重用性和易于测试奠定基础。 您是否曾尝试在应用程序中进行手动依赖项注入? 即使使用当今许多现有的依赖项注入库,由于您的项目越来越大,它仍需要大量样板代码,因为您必须手动构造每个类及其依赖项,并创建容器以重用和管理依赖项。

By following DI principles, you lay the groundwork for good app architecture, greater code reusability, and ease of testing.

通过遵循DI原则,您将为良好的应用程序体系结构,更高的代码可重用性和易于测试奠定基础

The new Hilt library defines a standard way to do DI in your application by providing containers for every Android class in your project and managing their lifecycles automatically for you. Hilt is currently in alpha, try it in your app and give us feedback using this link.

通过为项目中的每个Android类提供容器并为您自动管理其生命周期,新的Hilt库定义了一种在应用程序中执行DI的标准方法 。 Hilt目前处于Alpha状态 ,请在您的应用中进行尝试,并使用此链接向我们提供反馈。

Hilt is built on top of the popular DI library Dagger so benefits from the compile time correctness, runtime performance, scalability, and Android Studio support that Dagger provides. Due to this, Dagger’s seen great adoption on 74% of top 10k apps of the Google Play Store. However, because of the compile time code generation, expect a build time increase.

Hilt基于流行的DI库Dagger构建,因此可以从Dagger提供的编译时间正确性,运行时性能,可伸缩性和 Android Studio支持中受益。 因此,Dagger在Google Play商店的前10k顶级应用中占74%的广泛采用率。 但是,由于生成了编译时代码,因此预期编译时间会增加。

Since many Android framework classes are instantiated by the OS itself, there’s an associated boilerplate when using Dagger in Android apps. Unlike Dagger, Hilt is integrated with Jetpack libraries and Android framework classes and removes most of that boilerplate to let you focus on just the important parts of defining and injecting bindings without worrying about managing all of the Dagger setup and wiring. It automatically generates and provides:

由于许多Android框架类是由操作系统本身实例化的,因此在Android应用中使用Dagger时会有一个关联的样板。 与Dagger不同,Hilt与Jetpack库和Android框架类集成在一起,并删除了大部分样板,使您可以专注于定义和注入绑定的重要部分 ,而不必担心管理所有Dagger设置和接线。 它会自动生成并提供:

  • Components for integrating Android framework classes with Dagger that you would otherwise need to create by hand.

    用于将Android框架类与Dagger 集成的组件,否则需要手工创建。

  • Scope annotations for the components that Hilt generates automatically.

    Hilt自动生成的组件的范围注释

  • Predefined bindings and qualifiers.

    预定义的绑定和限定符

Best of all, as Dagger and Hilt can coexist together, apps can be migrated on an as-needed basis.

最重要的是, 由于Dagger和Hilt可以共存,因此可以根据需要迁移应用程序

行动中 (Hilt in action)

Just to show you how easy to use Hilt is, let’s perform some quick DI in a typical Android app. Let’s make Hilt inject an AnalyticsAdapter into our MainActivity.

只是为了向您展示Hilt的易用性,让我们在典型的Android应用中执行一些快速DI。 让我们让Hilt将AnalyticsAdapter注入到MainActivity

First, enable Hilt in your app by annotating your application class with the @HiltAndroidApp to trigger Hilt’s code generation:

首先,通过使用@HiltAndroidApp注释应用程序类以触发Hilt的代码生成,从而在应用程序中启用Hilt:

@HiltAndroidApp
class MyApplication : Application() { ... }

Second, tell Hilt how to provide instances of AnalyticsAdapter by annotating its constructor with @Inject:

第二,告诉希尔特如何提供的实例AnalyticsAdapter通过注释它的构造@Inject

class AnalyticsAdapter @Inject constructor() { ... }

And third, to inject an instance of AnalyticsAdapter into MainActivity, enable Hilt in the activity with the @AndroidEntryPoint annotation and perform field injection using the @Inject annotation:

第三,将AnalyticsAdapter的实例注入MainActivity ,在活动中使用@AndroidEntryPoint批注启用Hilt并使用@Inject批注执行字段注入:

@AndroidEntryPoint
class MainActivity : AppCompatActivity() { @Inject lateinit var analytics: AnalyticsAdapter override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) // analytics instance has been populated by Hilt
// and it's ready to be used
}
}

For more information, you can easily check out what the new annotations do in the cheat sheet section below.

有关更多信息,您可以在下面的备忘单部分中轻松查看新注释的功能。

随附Jetpack支持! (Comes with Jetpack support!)

You can use your favourite Jetpack libraries with Hilt out of the box. We’re providing direct injection support for ViewModel and WorkManager in this release.

您可以在开箱即用的情况下使用喜爱的Jetpack库。 在此版本中,我们为ViewModel和WorkManager提供直接注入支持

For example, to inject a Architecture Components ViewModel LoginViewModel into a LoginActivity: annotate LoginViewModel with @ViewModelInject and use it in the activity or fragment as you’d expect:

例如,要将架构组件ViewModel LoginViewModel注入LoginActivity :用@ViewModelInject注释LoginViewModel @ViewModelInject预期在活动或片段中使用它:

class LoginViewModel @ViewModelInject constructor(
private val analyticsAdapter: AnalyticsAdapter
): ViewModel { ... }@AndroidEntryPoint
class LoginActivity : AppCompatActivity() { private val loginViewModel: LoginViewModel by viewModels() override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// loginViewModel is ready to be used
}
}

Learn more about Jetpack support in the docs.

文档中了解有关Jetpack支持的更多信息。

开始使用Hilt (Start using Hilt)

If you’re intrigued by Hilt and want to learn more about it, here’s some resources for you to learn in the way you prefer:

如果您对Hilt感兴趣,并且想了解更多有关此的信息,请按照以下偏好的方式学习一些资源:

Hilt入门 (Getting started with Hilt)

Learn how to add Hilt in your Android app with this guide.

借助本指南,了解如何在您的Android应用中添加Hilt。

文献资料 (Documentation)

If you’re new to DI or Dagger, check out our guide to add Hilt to an Android app. Alternatively, if you already know Dagger, we’re also providing documentation on dagger.dev.

如果您不熟悉DI或Dagger,请查看我们的指南,将Hilt添加到Android应用中 。 另外,如果您已经了解Dagger,我们还将提供有关dagger.dev的文档

If you’re just curious about the new annotations and what you can do with Hilt, check out this cheat sheet in the section below.

如果您只是对新的注解以及Hilt的功能感到好奇,请在以下部分中查看该备忘单。

对于Dagger用户 (For Dagger users)

If you’re already using Dagger or dagger.android in your app, check out this migration guide or the codelab mentioned below to help you switch to Hilt. As Dagger and Hilt can coexist together, you can migrate your app incrementally.

如果您已经在应用程序中使用了Dagger或dagger.android,请查看此迁移指南或下面提到的代码实验室,以帮助您切换到Hilt。 由于Dagger和Hilt可以共存,因此您可以逐步迁移应用程序。

代码实验室 (Codelabs)

To learn Hilt in a step-by-step approach, we just released two codelabs:

为了逐步学习Hilt,我们刚刚发布了两个代码实验室:

样例代码 (Sample code)

Do you want to see how Hilt is used in existing apps? Go check its usage in the Google I/O 2020 app and in the dev-hilt branch of the Android architecture-samples Github repository.

您想查看在现有应用中如何使用Hilt吗? 在Google I / O 2020应用程序和Android 体系结构示例Github存储库dev-hilt分支中检查其用法。

反馈 (Feedback)

Hilt is currently in alpha, try it in your app and give us feedback using this link.

Hilt目前处于Alpha状态 ,请在您的应用中进行尝试,并使用此链接向我们提供反馈。

备忘单 (Cheat sheet)

This cheat sheet allows you to quickly see what the different Hilt and Dagger annotations do and how to use them.

这种小抄可以让你快速了解不同希尔特和匕首注释做,以及如何使用它们。

Download cheat sheet in PDF

下载PDF备忘单

翻译自: https://medium.com/androiddevelopers/dependency-injection-on-android-with-hilt-67b6031e62d

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Hilt 是一个用于简化依赖注入的框架,可以在 Android 应用程序中使用它来管理和注入依赖项。下面是使用 Hilt 进行依赖注入的一个简单示例应用: 1. 添加 Hilt 相关依赖到项目中。在项目的根目录的 `build.gradle` 文件中添加 Hilt Gradle 插件的依赖: ```groovy buildscript { repositories { ... } dependencies { ... classpath 'com.google.dagger:hilt-android-gradle-plugin:<version>' } } ``` 在应用模块的 `build.gradle` 文件中应用 Hilt 插件,并添加 Hilt 相关依赖: ```groovy apply plugin: 'kotlin-kapt' apply plugin: 'dagger.hilt.android.plugin' android { ... } dependencies { implementation 'com.google.dagger:hilt-android:<version>' kapt 'com.google.dagger:hilt-android-compiler:<version>' ... } ``` 2. 在 Application 类上添加 `@HiltAndroidApp` 注解,将其标记为 Hilt 应用程序: ```kotlin import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class MyApp : Application() { // Application 的实现代码... } ``` 3. 创建一个需要依赖注入的类,例如 UserRepository: ```kotlin import javax.inject.Inject class UserRepository @Inject constructor() { // UserRepository 的实现代码... } ``` 4. 在需要进行依赖注入的类中,使用 `@Inject` 注解来标记需要注入依赖项。例如,在 MainActivity 中: ```kotlin import javax.inject.Inject @AndroidEntryPoint class MainActivity : AppCompatActivity() { @Inject lateinit var userRepository: UserRepository // Activity 的实现代码... } ``` 通过以上步骤,Hilt 会自动管理依赖项的创建和注入。在 MainActivity 中,`userRepository` 字段将会被自动注入一个 UserRepository 实例。 需要注意的是,使用 Hilt 进行依赖注入需要在 Android Studio 中启用 kapt 插件。 这只是一个简单的示例,Hilt 可以在更复杂的应用程序中提供更多的依赖注入功能和灵活性。 希望对你有所帮助!如果还有其他问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值