Dagger 2技术疑问:如何注入@Provides方法内创建对象的依赖?
Alright, let's figure out why your Wheels instance isn't getting injected into Bike when you call BikeComponent.bike(). The core issue is how Dagger handles dependency injection for your Bike object—let's break down the fixes step by step.
1. Use Constructor Injection (Recommended Approach)
Constructor injection is Dagger's preferred method because it makes your dependencies explicit and ensures they're initialized when the object is created. Here's how to adjust your code:
First, update the Bike class to include an @Inject-annotated constructor that accepts both serial and Wheels:
public class Bike { String serial; Wheels wheels; @Inject public Bike(String serial, Wheels wheels) { this.serial = serial; this.wheels = wheels; } }
Then modify your BikeModule's provideBike method to accept a Wheels parameter—Dagger will automatically inject this since you already have a provideWheels method:
@Module public class BikeModule { @Provides public Bike provideBike(Wheels wheels) { return new Bike("BIK-001", wheels); } @Provides public Wheels provideWheels() { return new Wheels("WLS-027"); } }
Now when you call bikeComponent.bike(), Dagger will first create the Wheels instance, pass it to the Bike constructor, and your Wheels variable will be properly initialized.
2. Trigger Member Injection (If You Need to Keep Member Variables)
If you absolutely need to keep the @Inject annotation on the Wheels member variable, you'll need to tell Dagger to explicitly inject that member after creating the Bike instance.
First, add an injection method to your BikeComponent:
@Component(modules = BikeModule.class) public interface BikeComponent { Bike bike(); void inject(Bike bike); // Add this method to trigger member injection }
Then, after getting your Bike instance, call the inject method to populate the Wheels variable:
BikeComponent component = DaggerBikeComponent.create(); Bike bike = component.bike(); component.inject(bike); // This line injects the @Inject-marked Wheels member
Note: This approach is less reliable than constructor injection—it's easy to forget the inject call, and your dependencies aren't clearly visible from the constructor. Stick with constructor injection whenever possible.
Why Your Original Code Failed
In your original setup, you're creating the Bike instance directly in provideBike with new Bike("BIK-001"). Dagger only returns this pre-created object—it doesn't automatically scan or inject @Inject-marked member variables unless it's responsible for creating the object (via an @Inject constructor) or you explicitly trigger member injection.
内容的提问来源于stack exchange,提问作者Milack27

