← Learning Hub
Beginner

Beans and Dependency Injection

In Spring, you don't create your service objects with new. Spring creates them (they're called beans) and injects them where they're needed. This is dependency injection, and it's the core idea of Spring.

Dependency injection is the core idea of Spring: classes say what they need in their constructor, and Spring provides it. This keeps classes loosely connected, easy to swap and easy to test with fakes.

The idea in plain Java

Example
You can edit this code.

Because OrderService receives its notifier, you can swap it (or use a fake one in tests) without changing OrderService. Spring does the "giving" part automatically.

The same in Spring

Example
@Service                                    // Spring creates one of these and manages it
public class PriceService {
    public int withGst(int price) { return Math.round(price * 1.18f); }
}

@RestController
public class PriceController {
    private final PriceService prices;

    public PriceController(PriceService prices) {   // Spring passes the bean in
        this.prices = prices;
    }

    @GetMapping("/api/price")
    public int price(@RequestParam int base) {
        return prices.withGst(base);                 // /api/price?base=1000 -> 1180
    }
}

Stereotype annotations

  • @Component - a general bean
  • @Service - business logic
  • @Repository - database access
  • @RestController - web requests
  • @Configuration + @Bean methods - create beans yourself, for example for a library class
Use constructor injection as shown, with final fields. It's clear, works without Spring in tests, and is what the Spring team recommends.
Key points
  • Spring creates and manages beans.
  • Use constructor injection with final fields.
  • @Service, @Repository, @Component mark beans.

📝 Test yourself

1. What is a Spring bean?
2. What's the recommended way to inject a dependency?
3. Fill in the annotation for a business-logic class:
@ public class PriceService { }