Spring Boot, IoC & Dependency Injection
What Spring actually does when your app starts. The container, beans, constructor injection, auto-configuration and starters.
The concept
Inversion of Control (IoC) means your classes don’t build their own collaborators. Something else, the container, builds them and passes them in. Passing them in is called Dependency Injection (DI).
Without DI:
class CheckoutService {
private final OrderRepository orders = new JpaOrderRepository(new DataSource(/*...*/)); // hard-wired
private final PaymentGateway gateway = new StripePaymentGateway("<hard-coded-key>"); // untestable
}
With DI:
@Service
class CheckoutService {
private final OrderRepository orders;
private final PaymentGateway gateway;
CheckoutService(OrderRepository orders, PaymentGateway gateway) { // Spring passes these in
this.orders = orders;
this.gateway = gateway;
}
}
Now a test can pass a fake PaymentGateway, and production can swap Stripe for something else without touching CheckoutService.
What happens at startup
SpringApplication.runcreates the ApplicationContext, which is the container.- Component scanning finds classes annotated
@Component,@Service,@Repository,@Controller/@RestControllerand@Configurationunder your main package. - Classes marked
@Configurationcontribute@Beanfactory methods. - Auto-configuration adds beans based on what’s on the classpath and in config. For example, if the PostgreSQL driver is present and
spring.datasource.urlis set, you get aDataSource, a Hikari pool and anEntityManagerFactoryfor free. Conditions like@ConditionalOnClass,@ConditionalOnMissingBeanand@ConditionalOnPropertydecide what is created. - Spring resolves the dependency graph, instantiates the singletons, runs
@PostConstructand starts the embedded Tomcat.
Bean scopes
- singleton (the default): one instance per container. Your services are shared across all threads, so they must be stateless or thread-safe.
- prototype: a new instance every time the bean is injected or looked up.
- request and session: web-scoped instances.
Starters
A starter is a dependency bundle. For example, spring-boot-starter-data-jpa brings Hibernate, Spring Data, Hikari and the matching auto-configuration. All your projects use starters such as webmvc, security, data-jpa, validation, mail and actuator.
In your projects
module/booking/service/BookingService.javaThe services use constructor injection via Lombok. @RequiredArgsConstructor generates a constructor for every final field, and Spring calls that constructor. There are no @Autowired fields.
@Service
@RequiredArgsConstructor
public class BookingService {
private final BookingRepository bookingRepository;
private final RoomRepository roomRepository;
// ...
}shared/infrastructure/storage/* (MediaStorageService)IR3D chooses a bean implementation from configuration using @ConditionalOnProperty. The same MediaStorageService interface is backed by Cloudinary or S3, depending on app.storage.provider:
@Service
@ConditionalOnProperty(name = "app.storage.provider", havingValue = "s3")
class S3StorageService implements MediaStorageService { /* ... */ }
@Service
@ConditionalOnProperty(name = "app.storage.provider", havingValue = "cloudinary")
class CloudinaryStorageService implements MediaStorageService { /* ... */ }IR3D handles payments (StubPaymentGateway vs Paystack), content matching and view tracking the same way. This is auto-configuration thinking applied to your own code.
config/StripeConfig.java@PostConstruct runs once the bean has been built, and is used here to initialise a static SDK:
@PostConstruct
public void init() { Stripe.apiKey = secretKey; }Alternatives
| Approach | Notes |
|---|---|
| Constructor injection (yours) | Recommended by the Spring team |
Field injection @Autowired |
Hides dependencies, can’t be final, needs reflection in tests |
| Setter injection | Only for genuinely optional dependencies |
| Manual wiring / service locator | No framework, but you write all the plumbing |
| Compile-time DI (Dagger, Micronaut, Quarkus) | Faster startup and less reflection, so it suits serverless and native images |
Related concepts you must know
- Proxies. Spring wraps beans in proxies to add
@Transactional,@Async,@Cacheableand@PreAuthorizebehaviour. A call from inside the same class (this.method()) bypasses the proxy, so the annotation silently does nothing. This “self-invocation” trap is covered in the transactions lesson. @Primaryand@Qualifier. These choose a bean when several implement the same interface. Hostel uses a named executor with@Async("notificationExecutor").- The bean lifecycle. Construct, inject,
@PostConstruct, use,@PreDestroy. - Startup runners.
ApplicationRunner/CommandLineRunnerrun code at startup. Examples are IR3D’sAdminSeederand RM’sPermissionDataInitializer. - Profiles (
@Profile("prod")). Covered in the configuration lesson.