使用Dagger 2是否需注入所有对象?基础Java类如String等需注入吗?
Hey there! As someone who’s navigated the Dagger learning curve, I totally get this confusion—let’s break down when to use injection and when to skip it, clearly.
When to Use Dagger Injection (and When to Skip It)
Objects You Never Need to Inject
- Basic Java/Kotlin value types & lightweight objects: Things like
String,StringBuilder,ArrayList, primitive types (int,boolean)—these are simple, short-lived, and require no external dependencies to create. In your example, creating aStringBuilderdirectly inside thecreatemethod is exactly what you should do. Injecting these would only add unnecessary boilerplate and complicate your Dagger setup for zero practical benefit.
Objects That Should Be Injected
Focus on objects that fit one or more of these criteria:
- Android framework components with dependencies: Like
Context(stick toApplicationcontext for singletons to avoid memory leaks),ViewModel(especially with Dagger Hilt),Room Databaseinstances, orRetrofitservices. These often rely on other objects to be initialized correctly. - Custom business logic classes: Think
Repositoryclasses,NetworkManager,UserSessionManager—any class that has its own dependencies (e.g., aUserRepositoryneeding aUserDaoandApiService). Injecting these decouples your code, makes testing easier (you can swap in mock implementations), and centralizes object creation logic. - Singleton or scoped objects: If you need a single instance of an object across your app (like a global cache) or within a specific lifecycle scope (e.g., an Activity’s lifespan), Dagger’s scoping annotations (
@Singleton,@ActivityScoped) handle this cleanly without you having to manage singletons manually.
Quick Rule of Thumb to Decide
Ask yourself three simple questions:
- Does this object have a chain of dependencies (e.g., it needs other objects to function)? If yes, inject it.
- Will this object be reused across multiple parts of the app? If yes, inject it.
- Do I need to easily swap its implementation (e.g., for testing with mocks)? If yes, inject it.
If none of these apply—like your StringBuilder example—just create it directly with new.
内容的提问来源于stack exchange,提问作者Mohammed Daoud
相关产品推荐
相关产品推荐

