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.
ApplicationContextis the main Spring container.BeanFactoryis the basic IoC container.BeanDefinitionis the metadata recipe; the bean is the actual object.- Constructor injection is preferred for required dependencies.
@Primaryselects a default bean.@Qualifierselects a specific bean.
Direct Book Links
- What Problem Does Spring Solve?
- ApplicationContext and BeanFactory
- Beans and Bean Definitions
- Dependency Injection Deep Dive
- Component Scanning and Package Structure
- Week 1 Review
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.