Skip to main content

Spring Core and Dependency Injection

Cert Focus

You should be able to explain how Spring creates, wires, configures, and manages objects.

Must Know

  • IoC means control of object creation moves to the Spring container.
  • Dependency Injection means dependencies are provided from outside.
  • A bean is an object managed by the Spring IoC container.
  • ApplicationContext is the main Spring container.
  • BeanFactory is the basic IoC container.
  • BeanDefinition is the metadata recipe; the bean is the actual object.
  • Constructor injection is preferred for required dependencies.
  • @Primary selects a default bean.
  • @Qualifier selects a specific bean.

Exam Trap

@Service does not magically create a bean by itself. The class must be discovered by component scanning or registered another way.

Self-Check

  • Can I explain why new OrderRepository() creates tight coupling?
  • Can I explain IoC vs Dependency Injection?
  • Can I explain why constructor injection is preferred?
  • Can I explain what happens if two beans match one dependency?
Model Answers

new OrderRepository() creates tight coupling because OrderService decides the exact dependency implementation itself. It is harder to replace, configure, or mock.

IoC is the principle: Spring controls object creation and wiring. Dependency Injection is the technique: objects receive dependencies from outside instead of creating them.

Constructor injection is preferred because required dependencies are explicit, fields can be final, and tests can instantiate the class directly.

If two beans match one dependency, Spring usually fails with an ambiguity error unless one bean is selected with @Primary, @Qualifier, a specific type, or collection injection.

Memory Sentence

IoC is the idea; Dependency Injection is the main Spring technique.