• Stars
    star
    1,310
  • Rank 35,926 (Top 0.8 %)
  • Language
    Kotlin
  • License
    Apache License 2.0
  • Created over 4 years ago
  • Updated 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A Kotlin compiler plugin to make dependency injection with Dagger 2 easier.

Anvil

Maven Central CI

"When all you have is an anvil, every problem looks like a hammer." - Abraham Maslow

Anvil is a Kotlin compiler plugin to make dependency injection with Dagger easier by automatically merging Dagger modules and component interfaces. In a nutshell, instead of manually adding modules to a Dagger component and making the Dagger component extend all component interfaces, these modules and interfaces can be included in a component automatically:

@Module
@ContributesTo(AppScope::class)
class DaggerModule { .. }

@ContributesTo(AppScope::class)
interface ComponentInterface {
  fun getSomething(): Something
  fun injectActivity(activity: MyActivity)
}

// The real Dagger component.
@MergeComponent(AppScope::class)
interface AppComponent

The generated AppComponent interface that Dagger sees looks like this:

@Component(modules = [DaggerModule::class])
interface AppComponent : ComponentInterface

Notice that AppComponent automatically includes DaggerModule and extends ComponentInterface.

Setup

The plugin consists of a Gradle plugin and Kotlin compiler plugin. The Gradle plugin automatically adds the Kotlin compiler plugin and annotation dependencies. It needs to be applied in all modules that either contribute classes to the dependency graph or merge them:

plugins {
  id 'com.squareup.anvil' version "${latest_version}"
}

Or you can use the old way to apply a plugin:

buildscript {
  repositories {
    mavenCentral()
  }
  dependencies {
    classpath "com.squareup.anvil:gradle-plugin:${latest_version}"
  }
}

apply plugin: 'com.squareup.anvil'

Quick Start

There are three important annotations to work with Anvil.

@ContributesTo can be added to Dagger modules and component interfaces that should be included in the Dagger component. Classes with this annotation are automatically merged by the compiler plugin as long as they are on the compile classpath.

@MergeComponent is used instead of the Dagger annotation @Component. Anvil will generate the Dagger annotation and automatically include all modules and component interfaces that were contributed the same scope.

@MergeSubcomponent is similar to @MergeComponent and should be used for subcomponents instead.

Scopes

Scope classes are only markers. The class AppScope from the sample could look like this:

abstract class AppScope private constructor()

These scope classes help Anvil make a connection between the Dagger component and which Dagger modules and other component interfaces to include.

Scope classes are independent of the Dagger scopes. It's still necessary to set a scope for the Dagger component, e.g.

@Singleton
@MergeComponent(AppScope::class)
interface AppComponent

Contributed bindings

The @ContributesBinding annotation generates a Dagger binding method for an annotated class and contributes this binding method to the given scope. Imagine this example:

interface Authenticator

class RealAuthenticator @Inject constructor() : Authenticator

@Module
@ContributesTo(AppScope::class)
abstract class AuthenticatorModule {
  @Binds abstract fun bindRealAuthenticator(authenticator: RealAuthenticator): Authenticator
}

This is a lot of boilerplate if you always want to use RealAuthenticator when injecting Authenticator. You can replace this entire Dagger module with the @ContributesBinding annotation. The equivalent would be:

interface Authenticator

@ContributesBinding(AppScope::class)
class RealAuthenticator @Inject constructor() : Authenticator

@ContributesBinding also supports qualifiers. You can annotate the class with any qualifier and the generated binding method will preserve the qualifier, e.g.

@ContributesBinding(AppScope::class)
@Named("Prod")
class RealAuthenticator @Inject constructor() : Authenticator

// Will generate:
@Binds @Named("Prod") 
abstract fun bindRealAuthenticator(authenticator: RealAuthenticator): Authenticator

Contributed multibindings

Similar to contributed bindings, @ContributesMultibinding will generate a multibindings method for (all/an) annotated class(es). Qualifiers are supported the same way as normal bindings.

@ContributesMultibinding(AppScope::class)
@Named("Prod")
class MainListener @Inject constructor() : Listener

// Will generate this binding method.
@Binds @IntoSet @Named("Prod")
abstract fun bindMainListener(listener: MainListener): Listener

If the class is annotated with a map key annotation, then Anvil will generate a maps multibindings method instead of adding the element to a set:

@MapKey
annotation class BindingKey(val value: String)

@ContributesMultibinding(AppScope::class)
@BindingKey("abc")
class MainListener @Inject constructor() : Listener

// Will generate this binding method.
@Binds @IntoMap @BindingKey("abc")
abstract fun bindMainListener(listener: MainListener): Listener

Exclusions

Dagger modules and component interfaces can be excluded in two different levels.

One class can always replace another one. This is especially helpful for modules that provide different bindings for instrumentation tests, e.g.

@Module
@ContributesTo(
    scope = AppScope::class,
    replaces = [DevelopmentApplicationModule::class]
)
object DevelopmentApplicationTestModule {
  @Provides
  fun provideEndpointSelector(): EndpointSelector = TestingEndpointSelector
}

The compiler plugin will find both classes on the classpath. Adding both modules DevelopmentApplicationModule and DevelopmentApplicationTestModule to the Dagger graph would lead to duplicate bindings. Anvil sees that the test module wants to replace the other and ignores it. This replacement rule has a global effect for all applications which are including the classes on the classpath.

Applications can exclude Dagger modules and component interfaces individually without affecting other applications.

@MergeComponent(
  scope = AppScope::class,
  exclude = [
    DaggerModule::class
  ]
)
interface AppComponent

In a perfect build graph itโ€™s unlikely that this feature is needed. However, due to legacy modules, wrong imports and deeply nested dependency chains applications might need to make use of it. The exclusion rule does what it implies. In this specific example DaggerModule wishes to be contributed to this scope, but it has been excluded for this component and thus is not added.

Dagger Factory Generation

Anvil allows you to generate Factory classes that usually the Dagger annotation processor would generate for @Provides methods, @Inject constructors and @Inject fields. The benefit of this feature is that you don't need to enable the Dagger annotation processor in this module. That often means you can skip KAPT and the stub generating task. In addition Anvil generates Kotlin instead of Java code, which allows Gradle to skip the Java compilation task. The result is faster builds.

anvil {
  generateDaggerFactories = true // default is false
}

In our codebase we measured that modules using Dagger build 65% faster with this new Anvil feature compared to using the Dagger annotation processor:

Stub generation Kapt Javac Kotlinc Sum
Dagger 12.976 40.377 8.571 10.241 72.165
Anvil 0 0 6.965 17.748 24.713

For full builds of applications we measured savings of 16% on average.

Benchmark Dagger Factories

This feature can only be enabled in Gradle modules that don't compile any Dagger component. Since Anvil only processes Kotlin code, you shouldn't enable it in modules with mixed Kotlin / Java sources either.

When you enable this feature, don't forget to remove the Dagger annotation processor. You should keep all other dependencies.

Extending Anvil

Every codebase has its own dependency injection patterns where certain code structures need to be repeated over and over again. Here Anvil comes to the rescue and you can extend the compiler plugin with your own CodeGenerator. For usage please take a look at the compiler-api artifact

Advantages of Anvil

Adding Dagger modules to components in a large modularized codebase with many application targets is overhead. You need to know where components are defined when creating a new Dagger module and which modules to add when setting up a new application. This task involves many syncs in the IDE after adding new module dependencies in the build graph. The process is tedious and cumbersome. With Anvil you only add a dependency in your build graph and then you can immediately test the build.

Aligning the build graph and Dagger's dependency graph brings a lot of consistency. If code is on the compile classpath, then it's also included in the Dagger dependency graph.

Modules implicitly have a scope, if provided objects are tied to a scope. Now the scope of a module is clear without looking at any binding.

With Anvil you don't need any composite Dagger module anymore, which only purpose is to combine multiple modules to avoid repeating the setup for multiple applications. Composite modules easily become hairballs. If one application wants to exclude a module, then it has to repeat the setup. These forked graphs are painful and confusing. With Dagger you want to make the decision which modules fulfill dependencies as late as possible, ideally in the application module. Anvil makes this approach a lot easier by generating the code for included modules. Composite modules are redundant. You make the decision which bindings to use by importing the desired module in the application module.

Performance

Anvil is a convenience tool. Similar to Dagger it doesn't improve build speed compared to writing all code manually before running a build. The savings are in developer time.

The median overhead of Anvil is around 4%, which often means only a few hundred milliseconds on top. The overhead is marginal, because Kotlin code is still compiled incrementally and Kotlin compile tasks are skipped entirely, if nothing has changed. This doesn't change with Anvil.

Benchmark

On top of that, Anvil provides actual build time improvements by replacing the Dagger annotation processor in many modules if you enable Dagger Factory generation.

Kotlin compiler plugin

We investigated whether other alternatives like a bytecode transformer and an annotation processor would be a better option, but ultimately decided against them. For what we tried to achieve a bytecode transformer runs too late in the build process; after the Dagger components have been generated. An annotation processor especially when using KAPT would be too slow. Even though the Kotlin compiler plugin API isn't stable and contains bugs we decided to write a compiler plugin.

Limitations

No Java support

Anvil is a Kotlin compiler plugin, thus Java isnโ€™t supported. You can use Anvil in modules with mixed Java and Kotlin code for Kotlin classes, though.

Correct error types disabled

KAPT has the option to correct non-existent types. This option however changes order of how compiler plugins and KAPT itself are invoked. The result is that Anvil cannot merge supertypes before the Dagger annotation processor runs and abstract functions won't be implemented properly in the final Dagger component.

Anvil will automatically set correctErrorTypes to false to avoid this issue.

Incremental Kotlin compilation breaks Anvil's feature to merge contributions

Anvil merges Dagger component interfaces and Dagger modules during the stub generating task when @MergeComponent is used. This requires scanning the compile classpath for any contributions. Assume the scenario that a contributed type in a module dependency has changed, but the module using @MergeComponent itself didn't change. With Kotlin incremental compilation enabled the compiler will notice that the module using @MergeComponent doesn't need to be recompiled and therefore doesn't invoke compiler plugins. Anvil will miss the new contributed type from the module dependency.

To avoid this issue, Anvil must disable incremental compilation for the stub generating task, which runs right before Dagger processes annotations. Normal Kotlin compilation isn't impacted by this workaround. The issue is captured in KT-54850 Provide mechanism for compiler plugins to add custom information into binaries.

Disabling incremental compilation for the stub generating task could have a negative impact on compile times, if you heavily rely on KAPT. While Anvil can significantly help to improve build times, the wrong configuration and using KAPT in most modules could make things worse. The suggestion is to extract and isolate annotation processors in separate modules and avoid using Anvil in the same modules, e.g. a common practice is to move the Dagger component using @MergeComponent into the final application module with little to no other code in the app module.

Hilt

Hilt is Google's opinionated guide how to dependency injection on Android. It provides a similar feature with @InstallIn for entry points and modules as Anvil. If you use Hilt, then you don't need to use Anvil.

Hilt includes many other features and comes with some restrictions. For us it was infeasible to migrate a codebase to Hilt with thousands of modules and many Dagger components while we only needed the feature to merge modules and component interfaces automatically. We also restrict the usage of the Dagger annotation processor to only specific modules for performance reasons. With Hilt we wouldn't be able to enforce this requirement anymore for component interfaces. The development of Anvil started long before Hilt was announced and the internal version is being used in production for a while.

License

Copyright 2020 Square, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

More Repositories

1

okhttp

Squareโ€™s meticulous HTTP client for the JVM, Android, and GraalVM.
Kotlin
45,794
star
2

retrofit

A type-safe HTTP client for Android and the JVM
HTML
43,053
star
3

leakcanary

A memory leak detection library for Android.
Kotlin
29,383
star
4

picasso

A powerful image downloading and caching library for Android
Kotlin
18,716
star
5

javapoet

A Java API for generating .java source files.
Java
10,820
star
6

moshi

A modern JSON library for Kotlin and Java.
Kotlin
9,756
star
7

okio

A modern I/O library for Android, Java, and Kotlin Multiplatform.
Kotlin
8,790
star
8

dagger

A fast dependency injector for Android and Java.
Java
7,308
star
9

crossfilter

Fast n-dimensional filtering and grouping of records.
JavaScript
6,217
star
10

PonyDebugger

Remote network and data debugging for your native iOS app using Chrome Developer Tools
Objective-C
5,864
star
11

maximum-awesome

Config files for vim and tmux.
Ruby
5,706
star
12

otto

An enhanced Guava-based event bus with emphasis on Android support.
Java
5,163
star
13

cubism

Cubism.js: A JavaScript library for time series visualization.
JavaScript
4,943
star
14

sqlbrite

A lightweight wrapper around SQLiteOpenHelper which introduces reactive stream semantics to SQL operations.
Java
4,570
star
15

android-times-square

Standalone Android widget for picking a single date from a calendar view.
Java
4,445
star
16

wire

gRPC and protocol buffers for Android, Kotlin, Swift and Java.
Kotlin
4,244
star
17

Valet

Valet lets you securely store data in the iOS, tvOS, watchOS, or macOS Keychain without knowing a thing about how the Keychain works. Itโ€™s easy. We promise.
Swift
3,989
star
18

cube

Cube: A system for time series visualization.
JavaScript
3,904
star
19

kotlinpoet

A Kotlin API for generating .kt source files.
Kotlin
3,896
star
20

java-code-styles

IntelliJ IDEA code style settings for Square's Java and Android projects.
Shell
2,957
star
21

flow

Name UI states, navigate between them, remember where you've been.
Java
2,786
star
22

spoon

Distributing instrumentation tests to all your Androids.
HTML
2,702
star
23

keywhiz

A system for distributing and managing secrets
Java
2,619
star
24

tape

A lightning fast, transactional, file-based FIFO for Android and Java.
Java
2,466
star
25

certstrap

Tools to bootstrap CAs, certificate requests, and signed certificates.
Go
2,282
star
26

mortar

A simple library that makes it easy to pair thin views with dedicated controllers, isolated from most of the vagaries of the Activity life cycle.
Java
2,157
star
27

go-jose

An implementation of JOSE standards (JWE, JWS, JWT) in Go
1,975
star
28

Cleanse

Lightweight Swift Dependency Injection Framework
Swift
1,784
star
29

assertj-android

A set of AssertJ helpers geared toward testing Android.
Java
1,577
star
30

haha

DEPRECATED Java library to automate the analysis of Android heap dumps.
Java
1,436
star
31

phrase

Phrase is an Android string resource templating library
Java
1,404
star
32

cane

Code quality threshold checking as part of your build
Ruby
1,325
star
33

seismic

Android device shake detection.
Java
1,275
star
34

sudo_pair

Plugin for sudo that requires another human to approve and monitor privileged sudo sessions
Rust
1,240
star
35

square.github.io

A simple, static portal which outlines our open source offerings.
CSS
1,153
star
36

spacecommander

Commit fully-formatted Objective-C as a team without even trying.
Objective-C
1,126
star
37

workflow

A Swift and Kotlin library for making composable state machines, and UIs driven by those state machines.
Shell
1,124
star
38

workflow-kotlin

A Swift and Kotlin library for making composable state machines, and UIs driven by those state machines.
Kotlin
1,027
star
39

certigo

A utility to examine and validate certificates in a variety of formats
Go
941
star
40

logcat

I CAN HAZ LOGZ?
Kotlin
895
star
41

radiography

Text-ray goggles for your Android UI.
Kotlin
852
star
42

whorlwind

Makes fingerprint encryption a breeze.
Java
817
star
43

dagger-intellij-plugin

An IntelliJ IDEA plugin for Dagger which provides insight into how injections and providers are used.
Java
796
star
44

cycler

Kotlin
791
star
45

Paralayout

Paralayout is a set of simple, useful, and straightforward utilities that enable pixel-perfect layout in iOS. Your designers will love you.
Swift
786
star
46

apropos

A simple way to serve up appropriate images for every visitor.
Ruby
764
star
47

shift

shift is an application that helps you run schema migrations on MySQL databases
Ruby
735
star
48

coordinators

Simple MVWhatever for Android
Java
702
star
49

subzero

Block's Bitcoin Cold Storage solution.
C
683
star
50

Blueprint

Declarative UI construction for iOS, written in Swift
Swift
672
star
51

shuttle

String extraction, translation and export tools for the 21st century. "Moving strings around so you don't have to"
Ruby
656
star
52

gifencoder

A pure Java library implementing the GIF89a specification. Suitable for use on Android.
Java
654
star
53

pollexor

Java client for the Thumbor image service which allows you to build URIs in an expressive fashion using a fluent API.
Java
633
star
54

intro-to-d3

a D3.js tutorial
CSS
602
star
55

kochiku

Shard your builds for fun and profit
Ruby
599
star
56

curtains

Lift the curtain on Android Windows!
Kotlin
570
star
57

svelte-store

TypeScript
524
star
58

RxIdler

An IdlingResource for Espresso which wraps an RxJava Scheduler.
Java
511
star
59

burst

A unit testing library for varying test data.
Java
464
star
60

field-kit

FieldKit lets you take control of your text fields.
JavaScript
463
star
61

SuperDelegate

SuperDelegate provides a clean application delegate interface and protects you from bugs in the application lifecycle
Swift
454
star
62

otto-intellij-plugin

An IntelliJ IDEA plugin to navigate between events posted by Otto.
Java
451
star
63

js-jose

JavaScript library to encrypt/decrypt data in JSON Web Encryption (JWE) format and to sign/verify data in JSON Web Signature (JWS) format. Leverages Browser's native WebCrypto API.
JavaScript
422
star
64

sharkey

Sharkey is a service for managing certificates for use by OpenSSH
Go
395
star
65

connect-api-examples

Code samples demonstrating the functionality of the Square Connect API
JavaScript
391
star
66

fdoc

Documentation format and verification
Ruby
380
star
67

ETL

Extract, Transform, and Load data with Ruby
Ruby
377
star
68

lgtm

Simple object validation for JavaScript.
JavaScript
370
star
69

papa

PAPA: Performance of Android Production Applications
Kotlin
345
star
70

laravel-hyrule

Object-oriented, composable, fluent API for writing validations in Laravel
PHP
341
star
71

in-app-payments-flutter-plugin

Flutter Plugin for Square In-App Payments SDK
Objective-C
340
star
72

pylink

Python Library for device debugging/programming via J-Link
Python
331
star
73

workflow-swift

A Swift and Kotlin library for making composable state machines, and UIs driven by those state machines.
Swift
326
star
74

pysurvival

Open source package for Survival Analysis modeling
HTML
319
star
75

rails-auth

Modular resource-based authentication and authorization for Rails/Rack
Ruby
291
star
76

cocoapods-generate

A CocoaPods plugin that allows you to easily generate a workspace from a podspec.
Ruby
279
star
77

inspect

inspect is a collection of metrics gathering, analysis utilities for various subsystems of linux, mysql and postgres.
Go
268
star
78

Aardvark

Aardvark is a library that makes it dead simple to create actionable bug reports.
Objective-C
260
star
79

gradle-dependencies-sorter

A CLI app and Gradle plugin to sort the dependencies in your Gradle build scripts
Kotlin
253
star
80

jetpack

jet.pack: package your JRuby rack app for Jetty.
Ruby
248
star
81

luhnybin

Shell
232
star
82

auto-value-redacted

An extension for Google's AutoValue that omits redacted fields from toString().
Java
211
star
83

protoparser

Java parser for .proto schema declarations.
Java
210
star
84

squalor

Go SQL utility library
Go
205
star
85

Listable

Declarative list views for iOS apps.
Swift
200
star
86

p2

Platypus Platform: Tools for Scalable Deployment
Go
196
star
87

mimecraft

Utility for creating RFC-compliant multipart and form-encoded HTTP request bodies.
Java
195
star
88

git-fastclone

git clone --recursive on steroids
Ruby
187
star
89

zapp

Continuous Integration for KIF
Objective-C
179
star
90

metrics

Metrics Query Engine
Go
170
star
91

ruby-rrule

RRULE expansion for Ruby
Ruby
170
star
92

quotaservice

The purpose of a quota service is to prevent cascading failures in micro-service environments. The service acts as a traffic cop, slowing down traffic where necessary to prevent overloading services. For this to work, remote procedure calls (RPCs) between services consult the quota service before making a call. The service isnโ€™t strictly for RPCs between services, and can even be used to apply quotas to database calls, for example.
Go
153
star
93

wire-gradle-plugin

A Gradle plugin for generating Java code for your protocol buffer definitions with Wire.
Groovy
153
star
94

goprotowrap

A package-at-a-time wrapper for protoc, for generating Go protobuf code.
Go
148
star
95

beancounter

Utility to audit the balance of Hierarchical Deterministic (HD) wallets. Supports multisig + segwit wallets.
Go
144
star
96

rce-agent

gRPC-based Remote Command Execution Agent
Go
136
star
97

womeng_handbook

Everything you need to start or expand a women in engineering group in your community.
129
star
98

cocoapods-check

A CocoaPods plugin that shows differences between locked and installed Pods
Ruby
126
star
99

point-of-sale-android-sdk

A simple library for letting Point of Sale take in-store payments for your app using Point of Sale API.
Java
119
star
100

in-app-payments-react-native-plugin

Objective-C
119
star