BBackend CourseLeroy Labs
0/0
Search the course

Spring Boot, IoC & Dependency Injection

What Spring actually does when your app starts. The container, beans, constructor injection, auto-configuration and starters.

● beginnerSpring-Boot-StoreHostel-Web-AppReport-Manager-2IR3D (Kontentt)SperoTek (in dev)

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

  1. SpringApplication.run creates the ApplicationContext, which is the container.
  2. Component scanning finds classes annotated @Component, @Service, @Repository, @Controller/@RestController and @Configuration under your main package.
  3. Classes marked @Configuration contribute @Bean factory methods.
  4. 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.url is set, you get a DataSource, a Hikari pool and an EntityManagerFactory for free. Conditions like @ConditionalOnClass, @ConditionalOnMissingBean and @ConditionalOnProperty decide what is created.
  5. Spring resolves the dependency graph, instantiates the singletons, runs @PostConstruct and 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

Hostel-Web-Appmodule/booking/service/BookingService.java

The 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;
    // ...
}
IR3D (Kontentt)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.

Spring-Boot-Storeconfig/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
  • Proxies. Spring wraps beans in proxies to add @Transactional, @Async, @Cacheable and @PreAuthorize behaviour. 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.
  • @Primary and @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 / CommandLineRunner run code at startup. Examples are IR3D’s AdminSeeder and RM’s PermissionDataInitializer.
  • Profiles (@Profile("prod")). Covered in the configuration lesson.

Check yourself

1. Inside a service, method a() calls this.b(), and b() is annotated @Transactional. What happens?
2. Which annotation lets IR3D switch between S3 and Cloudinary via config?
3. Default bean scope?