I've come across a scenario where even though I hadn't explicitly included a module (via either @Module(includes = { .. } ) or @Component(modules = { .. })), dagger is able to construct all the classes just fine.
To make things more clear, here's the example Maven project I created:
src/
├── main
│ ├── java
│ │ └── org
│ │ └── daggertest
│ │ ├── Main.java
│ │ ├── persistence
│ │ │ ├── di
│ │ │ │ └── PersistenceModule.java
│ │ │ └── PersistenceManager.java
│ │ ├── ui
│ │ │ ├── AppUI.java
│ │ │ └── di
│ │ │ └── UIComponent.java
│ │ └── util
│ │ ├── di
│ │ │ └── UtilModule.java
│ │ └── SystemUtil.java
│ └── resources
└── test
└── java
There is a Main class and three packages (persistence, ui, util). There is a corresponding module for persistence and util. And a component for ui.
Let's start from the bottom. The UtilModule simply provides SystemUtil:
@Module
public class UtilModule {
@Provides
public SystemUtil providesSystemUtil() {
return new SystemUtil();
}
}
Pretty straightforward. Nothing going on here. As requested in the comments, here is how SystemUtil looks:
public class SystemUtil {
public Path getSomeFile(String fileName) {
return Path.of(fileName);
}
}
Then, in the persistence package, PersistanceManager injects SystemUtil. So PersistenceModule provides PersistenceManager like so:
@Module
public class PersistenceModule {
@Provides
public PersistenceManager providesPersistenceManager(SystemUtil systemUtil) {
return new PersistenceManager(systemUtil);
}
}
- Even though PersistenceModule doesn't explicitly include the module (by doing
@Module(includes = { UtilModule.class })), this works fine. Why?
Then, in the ui package, AppUI injects both PersistenceManager and SystemUtil. And I wrote UIComponent like so:
@Component(modules = { UtilModule.class })
public interface UIComponent {
AppUI buildAppUI();
}
- I only explicitly included the UtilModule. But it was still able to inject PersistenceManager even though I didn't specify the PersistenceModule. How is this able to work? Interestingly, if I don't include the UtilModule here, it fails.
My guess is that I have a misunderstanding of how the modules/components are able to isolate from each other.
- My expectation was that if it wasn't explicitly included in the Component or Module annotation, it would fail compilation. Is this not true? Is it possible to enforce this?
Please let me know if you need any other information. Thank you!