1. Understanding Inversion of Control (IoC Container)
Concept
Description
Container
ApplicationContext – manages beans
Bean
Object whose lifecycle is managed by container
DI
Container injects collaborators instead of new
Wiring
By type (default), by name (@Qualifier)
2. Creating Beans with @Component Annotation
Stereotype
Semantic Role
@Component
Generic Spring-managed bean
@Service
Business / domain logic
@Repository
Persistence — translates exceptions
@Controller
MVC controller (returns view names)
@RestController
@Controller + @ResponseBody
3. Creating Beans with @Service Annotation
Example: Service bean with constructor injection
@Servicepublic class OrderService { private final OrderRepository repo; public OrderService(OrderRepository repo) { this.repo = repo; } public Order place(NewOrder cmd) { return repo.save(Order.from(cmd)); }}
Best Practice
Reason
Keep services stateless
Singleton-safe
Inject via constructor
Immutable, testable
Return domain objects, not entities outside boundary
Decoupling
4. Creating Beans with @Repository Annotation
Feature
Effect
Exception translation
SQLException → DataAccessException
Stereotype
Identifies persistence layer
JPA repos
Auto-implemented from interface
5. Creating Beans with @Controller and @RestController
Example: @Controller returning a view
@Controllerpublic class HomeController { @GetMapping("/") String index(Model m) { m.addAttribute("name", "world"); return "index"; // template }}
Example: @RestController returning JSON
@RestController@RequestMapping("/api/users")public class UserApi { @GetMapping("/{id}") UserDto byId(@PathVariable long id) { /* … */ }}
6. Injecting Dependencies with @Autowired
Style
Recommended?
Constructor (no @Autowired needed since 4.3)
Yes — required deps, immutable
Setter
Optional deps
Field
Discouraged — hard to test
7. Using Constructor Injection
Example: Multi-dependency constructor injection
@Servicepublic class CheckoutService { private final PaymentGateway gateway; private final InventoryClient inventory; public CheckoutService(PaymentGateway g, InventoryClient i) { this.gateway = g; this.inventory = i; }}