humancode.us

Enabling Dagger in IntelliJ

December 1, 2022

I had a hard time getting Dagger to work in IntelliJ, so I’m writing down the steps so you will have an easier time at it.

Create a Java project using the usual settings.

IntelliJ default project creation dialog

Add Dagger2 dependencies to your project

  • Open your project’s module settings by right-clicking on your top-level project icon, and selecting Open Module Settings.
  • Click on the Dependencies tab.
  • Add a runtime dependency:
    • Press the + button.
    • Select the Library… From Maven option.
    • Enter com.google.dagger:dagger: in the search field.
      Maven module search dialog showing a search for “com.google.dagger:dagger:”
    • Select one of the versions (remember this version number)
    • When you return to the dependencies view, select the Runtime scope for the dependency.
  • Add a compile-time dependency:
    • Press the + button.
    • Select the Library… From Maven option.
    • Enter com.google.dagger:dagger-compiler: in the search field.
    • Select the same version number as the module you selected above.
    • When you return to the dependencies view, select the Compile scope for the dependency.

Project module dependencies dialog showing a runtime dependency on “google.dagger” and a compile-time dependency on “google.dagger.compiler”

Enable annotation processor support in the IDE

  • Open the IntelliJ preferences pane.
  • Navigate to the Build, Execution, Deployment entry, then Compiler and Annotation Processors.
  • Make sure Enable annotation processing is enabled.

General settings dialog showing “Enable annotation processing” checkbox checked for the project

Add generated sources to the code completion

  • Build your project. If things go well, you should see extra pre-compile tasks that generate code into a generated subdirectory in your output directory.
  • Right-click the generated subdirectory, Mark Directory As…, then Sources Root.

Main IDE view with a log of the program running to completion

And that should get you to building, autocompleting, and running your code with Dagger.