Java Spring core and dependency injection

The container, and what it actually does at startup. Nearly every Spring question that goes past the annotation reduces to bean lifecycle or proxying.

5 concepts · 15 interview questions · 1 answered in depth

Answered in depth

  • Why is constructor injection preferred over field injection?

    Constructor injection makes the dependency list part of the type, so a bean cannot be built wrong, its fields can be final, and a cycle fails immediately. Field injection wires in a second phase after construction, which is why it hides both a missing dependency and a circular one until something calls the method.

    Asked constantlyjunior1–8 yrs9 min read

What this topic covers

Every concept in spring core and dependency injection, and the questions each one gets asked as. Where a question links, it has a full write-up.

Inversion of control and dependency injection

The container constructs your objects and supplies their collaborators, so a class declares what it needs instead of deciding where to get it.

Declaring beans

Component scanning finds annotated classes; @Bean methods declare them explicitly. Which you use changes what you can configure.

  • What is the difference between @Component, @Service and @Repository?
  • When do you use @Bean instead of @Component?
  • How does component scanning decide what to pick up?

Bean scopes

Singleton by default, one instance per container — which is why mutable state on a bean is a concurrency bug rather than a style choice.

  • What is the default bean scope, and why does it matter?
  • How do you inject a prototype bean into a singleton?
  • What are request and session scopes, and how are they implemented?

Bean lifecycle

Instantiate, populate, run aware-interfaces and post-processors, initialise, then destroy. Post-processors are where proxies get created.

  • What are the phases of a bean's lifecycle?
  • What is a BeanPostProcessor, and what uses one?
  • @PostConstruct versus InitializingBean versus @Bean(initMethod)?

Ambiguity and cycles

Two candidates for one type, or two beans needing each other. Both are design signals as much as configuration errors.

  • How do you resolve two beans of the same type?
  • What happens on a circular dependency, and how do you fix it?
  • Why does constructor injection expose cycles that field injection hides?

More in Spring and Spring Boot

See the whole reference map →