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.
PreviousA teammate says "we use Spring, so of course this class does dependency injection" about a class that calls `applicationContext.getBean(PricingClient.class)` inside a method. Are they right?Next Two beans, `A` and `B`, each need the other. With constructor injection, Spring fails at startup and says so. With field injection, the exact same cycle can start successfully. What's the actual mechanism behind that difference, and is the field-injection version actually fine?