Dependency injectioneasy0-2 years

A `@Component` reads an `@Autowired` field inside its own constructor and gets `null`, even though the same field is populated correctly in every other method. What's actually happening, and why does constructor injection not have this problem?

Field injection happens by reflection, after the object is already constructed — so at the moment the constructor is running, nothing has written to that field yet, and reading it gets Java's default value (null for an object reference). Every other method runs later, once the container has finished populating the fields, which is why they see the real value. Constructor injection never has this window: a dependency taken as a constructor parameter is available the instant the object exists, because it was handed in as part of construction rather than written afterward. There is no point in a constructor-injected class's life where it exists but is only partially wired.

The lesson behind it →
More on Dependency injection