Dependency Injection, Beans and Spring Boot
45 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Spring is the centre of almost every Java backend interview. The interviewer checks that you can explain dependency injection with a small example, choose between beans, and say what Spring Boot sets up for you.
IoC and dependency injection
The IoC container (ApplicationContext) creates your objects, called beans, and gives each one the dependencies it needs. Inversion of Control means the framework, not your code, controls object creation and wiring.
A class that builds its helpers with new can never use another one. The first half of this example hard-codes an SMS sender; the second half receives it from outside.
Example 1 · Without and with dependency injection (plain Java)
interface Notifier { String send(String to, String msg);}
class SmsNotifier implements Notifier { public String send(String to, String msg) { return "SMS to " + to + ": " + msg; }}
class FakeNotifier implements Notifier { // used in tests int calls = 0;
public String send(String to, String msg) { calls++; return "(fake) " + msg; }}
class TightOrderService { private final Notifier notifier = new SmsNotifier(); // creates its own dependency
String place(String phone) { return notifier.send(phone, "Order placed"); }}
class OrderService { private final Notifier notifier;
OrderService(Notifier notifier) { // dependency is injected this.notifier = notifier; }
String place(String phone) { return notifier.send(phone, "Order placed"); }}
public class ManualDiDemo { public static void main(String[] args) { System.out.println(new TightOrderService().place("98100"));
System.out.println(new OrderService(new SmsNotifier()).place("98100"));
FakeNotifier fake = new FakeNotifier(); System.out.println(new OrderService(fake).place("98100")); System.out.println("fake was called " + fake.calls + " time(s)"); }}SMS to 98100: Order placed SMS to 98100: Order placed (fake) Order placed fake was called 1 time(s)
What this code does
TightOrderServicebuilds its ownSmsNotifier, so it can never use anything else.OrderServicereceives aNotifierin its constructor: that is dependency injection, with or without Spring.- Passing a
FakeNotifierlets a test check the logic without sending SMS. Spring's job is only to do this wiring for every class automatically.
Dependency injection (DI) is how Spring implements IoC: a class declares what it needs and the container supplies it. OrderService can then depend on a Notifier interface, and a test can pass a fake. ApplicationContext is the container; BeanFactory is its simpler parent.
Revise: Inversion of control (opens in a new tab), Beans and the ApplicationContext (opens in a new tab).
Constructor vs field injection
Constructor injection passes a bean its dependencies as constructor parameters. The fields can be final, the object is never half-built, and a unit test can create it with new. It is the recommended style for required dependencies.
Spring calls the only constructor and supplies the other beans. This example loads three beans, and no @Autowired is needed.
Example 2 · Spring creates the beans and injects them through constructors
Runs in: a Maven project with the spring-context dependency (Section 15)
import org.springframework.context.annotation.AnnotationConfigApplicationContext;import org.springframework.stereotype.Component;import org.springframework.stereotype.Repository;import org.springframework.stereotype.Service;
@Repositoryclass OrderRepository { int count = 0;
int save(String item) { return ++count; }}
@Componentclass SmsSender { String send(String msg) { return "SMS: " + msg; }}
@Serviceclass CheckoutService { private final OrderRepository repo; private final SmsSender sms;
CheckoutService(OrderRepository repo, SmsSender sms) { // constructor injection this.repo = repo; this.sms = sms; }
String checkout(String item) { int id = repo.save(item); return sms.send("order " + id + " for " + item + " placed"); }}
public class SpringDiDemo { public static void main(String[] args) { try (var ctx = new AnnotationConfigApplicationContext( OrderRepository.class, SmsSender.class, CheckoutService.class)) { CheckoutService service = ctx.getBean(CheckoutService.class); System.out.println(service.checkout("headphones")); System.out.println(service.checkout("charger")); System.out.println("same repository bean everywhere: " + (ctx.getBean(OrderRepository.class) == ctx.getBean(OrderRepository.class))); } }}SMS: order 1 for headphones placed SMS: order 2 for charger placed same repository bean everywhere: true
What this code does
- The context creates the three stereotype-annotated beans and calls
CheckoutService's only constructor with the other two; no@Autowiredis needed. In Spring Boot, component scanning finds them instead of the class list passed here. - Beans are singletons by default: every
getBean(OrderRepository.class)returns the same object, which is why the order count keeps rising.
Field injection (@Autowired on a private field) hides dependencies, cannot be final, and leaves the field null in a plain unit test. Setter injection suits optional dependencies. A circular dependency fails with constructor injection, and Spring Boot forbids cycles by default; the real fix is a redesign.
Find the bug
Spot the injection smell
One line in each class makes it hard to test. Click it.
A plain unit test does new ReportService() and gets a NullPointerException. Which line?
Round 1 of 2@Component, @Service, @Repository, @Controller and @Bean
@Component, @Service, @Repository and @Controller are stereotype annotations: component scanning turns each annotated class into a bean. The last three are specialised @Components that name the layer.
There are two ways to register a bean: annotate your own class, or write a method that returns the object. @Bean is for classes you cannot annotate.
@Repository also translates database exceptions into Spring's DataAccessException, and @Controller makes the class a web handler. @Bean goes on a method in a @Configuration class, for library classes such as a PasswordEncoder or when creation needs logic. Model answer: "@Component is class-level and found by scanning; @Bean is method-level and gives full control over how the object is built."
Revise: Stereotype annotations (opens in a new tab), @Bean methods (opens in a new tab), Component scanning (opens in a new tab).
Bean scopes and lifecycle
A bean scope says how many instances Spring creates. The default, singleton, gives one shared instance per container; prototype creates a new instance each time the bean is requested. Web apps add request and session scopes.
This example shows a singleton, a prototype and the lifecycle callbacks. The two payment gateways in it come back in the next section.
Example 3 · @Primary, @Qualifier, scopes and lifecycle callbacks
Runs in: a Maven project with the spring-context dependency (Section 15)
import jakarta.annotation.PostConstruct;import jakarta.annotation.PreDestroy;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.context.annotation.AnnotationConfigApplicationContext;import org.springframework.context.annotation.Primary;import org.springframework.context.annotation.Scope;import org.springframework.stereotype.Component;import org.springframework.stereotype.Service;
interface PaymentGateway { String pay(int amount);}
@Component("upi")@Primaryclass UpiGateway implements PaymentGateway { public String pay(int amount) { return "UPI paid Rs " + amount; }}
@Component("card")class CardGateway implements PaymentGateway { public String pay(int amount) { return "Card paid Rs " + amount; }}
@Component@Scope("prototype")class Cart {}
@Serviceclass PaymentService { private final PaymentGateway defaultGateway; private final PaymentGateway cardGateway;
PaymentService(PaymentGateway defaultGateway, @Qualifier("card") PaymentGateway cardGateway) { this.defaultGateway = defaultGateway; // @Primary wins: UpiGateway this.cardGateway = cardGateway; // @Qualifier picks CardGateway }
@PostConstruct void ready() { System.out.println("PaymentService ready (@PostConstruct)"); }
@PreDestroy void stop() { System.out.println("PaymentService closing (@PreDestroy)"); }
void run() { System.out.println(defaultGateway.pay(499)); System.out.println(cardGateway.pay(1299)); }}
public class QualifierScopeDemo { public static void main(String[] args) { try (var ctx = new AnnotationConfigApplicationContext( UpiGateway.class, CardGateway.class, Cart.class, PaymentService.class)) { ctx.getBean(PaymentService.class).run(); System.out.println("singleton same object: " + (ctx.getBean(PaymentService.class) == ctx.getBean(PaymentService.class))); System.out.println("prototype same object: " + (ctx.getBean(Cart.class) == ctx.getBean(Cart.class))); } System.out.println("context closed"); }}PaymentService ready (@PostConstruct) UPI paid Rs 499 Card paid Rs 1299 singleton same object: true prototype same object: false PaymentService closing (@PreDestroy) context closed
What this code does
- Two beans implement
PaymentGateway. The unqualified parameter gets the@PrimaryUPI gateway;@Qualifier("card")picks the card gateway by bean name. @PostConstructruns after injection and@PreDestroywhen the context closes. The singletonPaymentServiceis one object; the prototypeCartis new on everygetBean.
A singleton is shared by every request thread, so it must be stateless or thread-safe. A prototype injected into a singleton is created only once; use ObjectProvider<T> to get a fresh one each time.
Order of execution
The bean lifecycle
Put the life of a singleton bean in order.
Two beans of one type: @Primary and @Qualifier
@Primary marks the default bean when several beans share a type. @Qualifier("name") at the injection point picks one specific bean, and it wins over @Primary.
Two classes implement PaymentGateway, so injection by type is ambiguous. In the previous example UpiGateway is @Primary, and the card gateway is picked with @Qualifier.
Without @Primary or @Qualifier, startup fails with NoUniqueBeanDefinitionException. You can also inject List<PaymentGateway> to receive every implementation. NoSuchBeanDefinitionException is the opposite problem: no bean of that type, so check scanning and annotations.
Predict the output
Which gateway is injected?
Both classes implement PaymentGateway.
Round 1 of 3
Which gateway does Checkout receive?
How Spring Boot auto-configuration works
Auto-configuration creates beans for you based on what is on the classpath and in your properties. Each one is guarded by a condition and backs off as soon as you define your own bean of that type.
Boot creates a default bean only when none exists. This example shows the same back-off pattern with two conditions.
Example 4 · Conditions: how auto-configuration backs off
Runs in: a Spring Boot 4 project (Section 15)
import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;
interface OtpSender { String send(String phone);}
class ConsoleOtpSender implements OtpSender { public String send(String phone) { return "OTP printed to console for " + phone; }}
class SmsOtpSender implements OtpSender { public String send(String phone) { return "OTP sent by SMS to " + phone; }}
@Configurationclass OtpConfig { @Bean @ConditionalOnProperty(name = "otp.mode", havingValue = "sms") OtpSender smsOtpSender() { // only when otp.mode=sms return new SmsOtpSender(); }
@Bean @ConditionalOnMissingBean(OtpSender.class) // a default that backs off OtpSender consoleOtpSender() { return new ConsoleOtpSender(); }}
@SpringBootApplication // = @SpringBootConfiguration + @EnableAutoConfiguration + @ComponentScanpublic class SAutoConfig { public static void main(String[] args) { var ctx = SpringApplication.run(SAutoConfig.class, args); System.out.println(ctx.getBean(OtpSender.class).send("98100")); }}(otp.mode not set) OTP printed to console for 98100 (otp.mode=sms) OTP sent by SMS to 98100
What this code does
- The SMS bean exists only when
otp.mode=sms(@ConditionalOnProperty). The console bean has@ConditionalOnMissingBean, so it is created only if no otherOtpSenderexists: the same back-off pattern Boot's own auto-configurations use. - Run once without the property and once with
--otp.mode=smsto see the two lines. Spring Boot's startup log is left out of the output shown.
@SpringBootApplication combines @SpringBootConfiguration, @ComponentScan (this package and below) and @EnableAutoConfiguration. Starters such as spring-boot-starter-web are dependency bundles. The conditions are @ConditionalOnClass, @ConditionalOnMissingBean and @ConditionalOnProperty; run with --debug to see the condition report.
Revise: Auto-configuration (opens in a new tab), Starters (opens in a new tab).
@RestController, error handling and profiles
@RestController is @Controller plus @ResponseBody: each handler's return value is written to the response body, usually as JSON, instead of being treated as a view name.
@Controller returns a page name; @RestController returns data. This example also shows one error handler for all controllers and a dev-only bean.
Example 5 · @RestController vs @Controller, @RestControllerAdvice and @Profile
Runs in: a Spring Boot 4 web project with Thymeleaf (Section 15); add a main class with @SpringBootApplication
import java.util.Map;
import org.springframework.context.annotation.Profile;import org.springframework.http.HttpStatus;import org.springframework.http.ProblemDetail;import org.springframework.stereotype.Controller;import org.springframework.stereotype.Service;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RestController;import org.springframework.web.bind.annotation.RestControllerAdvice;
class StudentNotFoundException extends RuntimeException { StudentNotFoundException(int roll) { super("No student with roll " + roll); }}
@Serviceclass StudentService { private final Map<Integer, String> names = Map.of(1, "Asha", 2, "Ravi");
String name(int roll) { String n = names.get(roll); if (n == null) throw new StudentNotFoundException(roll); return n; }}
@RestController // @Controller + @ResponseBody: returns data (JSON)class StudentApi { private final StudentService service;
StudentApi(StudentService service) { this.service = service; }
@GetMapping("/api/v1/students/{roll}") Map<String, Object> get(@PathVariable int roll) { return Map.of("roll", roll, "name", service.name(roll)); }}
@Controllerclass StudentPage { private final StudentService service;
StudentPage(StudentService service) { this.service = service; }
@GetMapping("/students/{roll}") String page(@PathVariable int roll, Model model) { model.addAttribute("name", service.name(roll)); return "student"; }}
@RestControllerAdvice // one place for errors from every controllerclass ApiErrors { @ExceptionHandler(StudentNotFoundException.class) ProblemDetail notFound(StudentNotFoundException e) { return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, e.getMessage()); }}
@Service@Profile("dev") // created only when the dev profile is activeclass DemoDataLoader {}
public class SControllerAdvice {}GET /api/v1/students/1 -> 200 {"roll":1,"name":"Asha"}
GET /api/v1/students/9 -> 404 {"type":"about:blank","title":"Not Found","status":404,"detail":"No student with roll 9","instance":"/api/v1/students/9"}
GET /students/1 -> HTML page rendered from templates/student.htmlWhat this code does
StudentApireturns aMapthat becomes JSON;StudentPagereturns the view namestudentfor a template. The service throws one exception, and the advice turns it into a 404 Problem Details response for every controller.DemoDataLoaderis created only when thedevprofile is active. JSON field order and theinstancefield can differ slightly between versions.
@RestControllerAdvice holds @ExceptionHandler methods that apply to every controller, so errors share one format such as Problem Details. Profiles switch configuration per environment (application-prod.properties, @Profile("dev"), spring.profiles.active=prod); secrets come from environment variables, not files in Git.
Revise: Controller advice (opens in a new tab), Profiles (opens in a new tab).
Find the bug
Spot the wrong annotation
One line in each snippet is wrong. Click it.
This endpoint should return JSON, but Spring looks for a view named "product". Which line?
Round 1 of 2Next step
Check your understanding
12 quick questions