Sub topic 1
Background: Spring Framework and Dependency Injection
Spring Boot sits on top of the Spring Framework. Most of what Boot does for you is easier to understand once you know what the framework underneath does. This chapter covers the part that matters most: the container that creates your objects and connects them. That mechanism is called dependency injection.
Prerequisites
This chapter assumes you have:
- Basic Java: classes, interfaces, constructors, and annotations as a user.
- A JDK 17 or newer and a terminal.
- Some familiarity with Maven or Gradle, enough to add a dependency.
- A rough idea of what an HTTP web application is.
You do not need any previous Spring experience.
The problem: objects that build their own collaborators
A typical application has classes that depend on other classes. A WelcomeService sends messages, so it needs something that can send them. The simplest approach is to create that helper inside the class:
package com.example.tight;
class SmtpSender {
void send(String to, String body) {
System.out.println("SMTP to " + to + ": " + body);
}
}
class WelcomeService {
private final SmtpSender sender = new SmtpSender();
void welcome(String user) {
sender.send(user, "Welcome, " + user + "!");
}
}
public class Main {
public static void main(String[] args) {
new WelcomeService().welcome("Ada");
}
}This works, but WelcomeService is now welded to SmtpSender. You cannot test the service without a real sender. You cannot switch to another sender without editing the service. If SmtpSender later needs its own dependencies, such as a host name or a connection pool, every class that calls new SmtpSender() has to change.
Inversion of control and dependency injection
The fix is to stop creating dependencies inside the class. The class declares what it needs, usually as constructor parameters, and something else supplies them.
- Inversion of control (IoC) is the general principle: your code does not control the creation and wiring of objects. A framework does, and it calls your code.
- Dependency injection (DI) is the technique Spring uses to apply IoC. The framework passes ("injects") each object's dependencies in from outside.
You can do DI without any framework. Write new WelcomeService(new SmtpSender()) in main, and you have done it. This is fine for three classes. With hundreds of classes, the wiring code becomes large and fragile. Spring automates that wiring.
The Spring container
The center of the Spring Framework is the container, represented by the ApplicationContext interface. It does four jobs:
- It reads bean definitions, which describe the objects it should manage.
- It creates those objects, called beans.
- It works out which beans depend on which, and injects them in the right order.
- It manages their lifecycle, from creation to shutdown.
A bean is an ordinary Java object. The only thing that makes it a bean is that the container created and manages it. Beans are singletons by default: the container creates one instance per bean definition and reuses it everywhere it is injected.
Declaring beans
There are two common ways to tell the container about a bean.
Stereotype annotations on your own classes. @Component marks a class as a bean. @Service, @Repository, and @Controller are specializations of @Component. They behave the same way for DI and signal the class's role. The container finds these classes through component scanning, enabled with @ComponentScan. It searches a base package and its sub-packages.
@Bean methods in a @Configuration class. Use this for classes you cannot annotate, such as library classes, or when construction needs custom logic. The method's return value becomes the bean:
package com.example.basics;
import java.time.Clock;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
class ClockConfig {
@Bean
Clock clock() {
return Clock.systemUTC();
}
}Other beans can now declare a Clock constructor parameter and receive this instance.
Injection styles
Spring can inject dependencies in three ways:
| Style | How it looks | Notes |
|---|---|---|
| Constructor | Dependencies are constructor parameters | Preferred. Fields can be `final`, and the object is never half-built. |
| Setter | A `@Autowired` setter method | Useful for optional dependencies. |
| Field | `@Autowired` directly on a field | Short, but hides dependencies and makes plain-Java tests harder. |
If a class has a single constructor, Spring uses it automatically. You do not need @Autowired on it.
A complete example
This example uses the container directly. Add the spring-context dependency first. In Maven it looks like this:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.2.0</version>
</dependency>Put the following in src/main/java/com/example/basics/Main.java. The classes share one file only for brevity. In a real project each gets its own file.
package com.example.basics;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
interface MessageSender {
void send(String to, String body);
}
@Component
class ConsoleSender implements MessageSender {
@Override
public void send(String to, String body) {
System.out.println("To " + to + ": " + body);
}
}
@Service
class WelcomeService {
private final MessageSender sender;
WelcomeService(MessageSender sender) {
this.sender = sender;
}
void welcome(String user) {
sender.send(user, "Welcome, " + user + "!");
}
}
@Configuration
@ComponentScan
class AppConfig {
}
public class Main {
public static void main(String[] args) {
try (var context = new AnnotationConfigApplicationContext(AppConfig.class)) {
context.getBean(WelcomeService.class).welcome("Ada");
}
}
}Running it prints To Ada: Welcome, Ada!. Here is what happened:
AppConfigis a configuration class. Its@ComponentScanhas no arguments, so it scans the packagecom.example.basicsand below.- The scan found
ConsoleSenderandWelcomeServiceand registered them as bean definitions. WelcomeServiceneeds aMessageSender. The container found thatConsoleSenderis the only bean of that type, created it first, and passed it to the constructor.WelcomeServicenever mentionsConsoleSender. To change how messages are sent, you add another implementation. In a test, you pass a fakeMessageSenderto the constructor with no Spring at all.
Notice that you never wrote new WelcomeService(...). The container did.
Common errors
Most first-week DI problems come from a few causes.
| Error or symptom | Usual cause | Fix |
|---|---|---|
| `NoSuchBeanDefinitionException` or "No qualifying bean of type" | The class is not annotated, or it is outside the scanned packages. | Add `@Component` or a `@Bean` method, and check the package location. |
| `NoUniqueBeanDefinitionException` | Two beans match the requested type. | Mark one `@Primary`, or select one with `@Qualifier("name")`. |
| `UnsatisfiedDependencyException` with a circular reference | Bean A needs B and B needs A through constructors. | Redesign so the cycle disappears, for example by extracting a third class. |
| Injected field is `null` | You created the object with `new`, so the container never saw it. | Obtain the object from the container, or inject it. |
| Nothing happens, no beans found | The context was built from a class with no `@ComponentScan` or `@Bean` methods. | Add `@ComponentScan` to the configuration class. |
Why this matters for Spring Boot
Everything above works on its own, and the Spring Framework has done so for many years. The cost is setup. You must choose and align library versions, write configuration classes, create the context yourself, and wire in a web server. Spring Boot keeps the same container and the same annotations. It automates the setup around them. The next chapter looks at what Boot adds and which problems it targets.
Exercise
In the complete example, you add a second class FileSender implements MessageSender and annotate it with @Component. What happens when the application starts, and name two ways to fix it?
Show answer
The container finds two beans of type MessageSender, so it cannot decide what to inject into WelcomeService. Startup fails with NoUniqueBeanDefinitionException (wrapped in an UnsatisfiedDependencyException). Fix it by marking one implementation @Primary, or by adding @Qualifier("consoleSender") to the constructor parameter. Bean names default to the decapitalized class name, so the qualifier value matches ConsoleSender as consoleSender. Removing @Component from one class also works.
Exercise
Why is constructor injection preferred over field injection for the sender dependency in WelcomeService?
Show answer
With constructor injection the field can be final, the dependency is visible in the class signature, and the object cannot exist without it. You can also create WelcomeService in a plain unit test with new WelcomeService(fakeSender), without starting Spring. Field injection needs reflection or the container to set the value, so the test setup is harder.