Lesson 1 of 12 · 10 min · Spring core
Spring dependency injection, beans and the container
What you will learn
- What a bean and the Spring container are
- Define beans with
@Component,@Service,@Repository,@Configurationand@Bean - Constructor injection and why it is preferred
- Bean scopes and the lifecycle callbacks
- Resolve two beans of the same type with
@Primaryand@Qualifier
In simple words
In a plain Java program you create every object yourself with new, and each object also creates the objects it needs. Spring flips that around. You describe the parts of your application, and Spring builds them and hands each one what it needs, like a manager who puts together a team and gives each person their tools. The objects Spring manages are called beans, and handing over their needs is dependency injection.
Words to know
- Bean: an object created and managed by the Spring container.
- Container (ApplicationContext): the part of Spring that creates beans and connects them.
- Dependency injection: Spring supplying the objects a class needs instead of the class creating them.
- Component scanning: Spring searching your packages for classes marked as components.
Why dependency injection
From the Core Java course (SOLID): code that depends on an interface and receives it from outside is easy to change and test. Spring automates the "receives it from outside" part.
public interface OrderRepository {
Order findById(long id);
}
@Service
public class OrderService {
private final OrderRepository repository;
public OrderService(OrderRepository repository) { // Spring passes the bean in
this.repository = repository;
}
public Order get(long id) {
return repository.findById(id);
}
}
OrderService never says which implementation it uses or how it is built. In production Spring injects the JPA-backed one; in a unit test you pass a fake.
The container and its beans
When the application starts, Spring creates an ApplicationContext: a registry of beans. It finds bean definitions, creates the objects in the right order (a bean's dependencies first), injects them, and keeps them. A Spring Boot application starts it with one call:
@SpringBootApplication
public class ShopApplication {
public static void main(String[] args) {
SpringApplication.run(ShopApplication.class, args);
}
}
@SpringBootApplication combines @Configuration, @EnableAutoConfiguration and @ComponentScan (next lessons).
Defining beans
1. Stereotype annotations on your own classes; Spring finds them by component scanning in the main class's package and sub-packages:
| Annotation | Meaning |
|---|---|
@Component |
a general Spring-managed class |
@Service |
business logic (the service layer) |
@Repository |
data access; also translates persistence exceptions |
@Controller / @RestController |
web layer |
@Configuration |
a class that declares beans |
@Service and @Repository behave like @Component; they document intent and some add behaviour.
2. @Bean methods in a @Configuration class, for classes you do not own or that need custom setup:
@Configuration
public class AppConfig {
@Bean
public Clock clock() { // bean name defaults to the method name: "clock"
return Clock.systemUTC();
}
@Bean
public RestClient paymentClient(RestClient.Builder builder) { // parameters are injected too
return builder.baseUrl("https://payments.example.com").build();
}
}
Put your code in packages below the main class (com.shop for the main class and com.shop.orders for services), or scanning will not find it.
Constructor injection
Spring can inject through a constructor, a setter or a field (@Autowired). Prefer constructor injection:
- Dependencies are required and cannot be forgotten.
- Fields can be
final, so the object is immutable and thread-safe. - Tests simply call
new OrderService(fakeRepository)with no Spring at all. - Circular dependencies show up immediately instead of hiding.
If a class has one constructor, Spring uses it without @Autowired. Avoid field injection (@Autowired private Repo repo;): it hides dependencies, cannot be final and needs reflection or Spring to test. Optional dependencies can be Optional<T>, ObjectProvider<T> or @Nullable.
Lombok's @RequiredArgsConstructor can generate the constructor, but plain Java (or a record-like style) is perfectly fine.
Several beans of the same type
If two beans match, Spring does not guess:
@Service class StripePayment implements PaymentGateway { ... }
@Service class RazorpayPayment implements PaymentGateway { ... }
@Service
class CheckoutService {
CheckoutService(PaymentGateway gateway) { ... } // NoUniqueBeanDefinitionException
}
Fix it in one of three ways:
@Primary @Service class RazorpayPayment ... // the default choice
CheckoutService(@Qualifier("stripePayment") PaymentGateway gateway) { ... } // pick by bean name
CheckoutService(List<PaymentGateway> gateways) { ... } // inject all of them
A Map<String, PaymentGateway> injects all beans keyed by bean name, a nice way to implement a strategy lookup.
Scopes
A bean's scope says how many instances exist:
| Scope | Instances |
|---|---|
singleton (default) |
one per container, shared by everyone |
prototype |
a new instance each time it is requested |
request, session, application |
one per HTTP request, session or servlet context (web apps) |
Most beans are singletons, so they must be stateless or thread-safe: many requests use the same instance at once. Never keep per-user or per-request data in a field of a singleton service. Pass it as method parameters or use request-scoped beans.
Lifecycle
Spring creates the bean, injects dependencies, runs initialisation callbacks, uses the bean, and on shutdown runs destroy callbacks:
@Component
public class CacheWarmer {
@PostConstruct
void warm() { /* runs after injection */ }
@PreDestroy
void cleanup() { /* runs on shutdown */ }
}
@Bean(initMethod = "...", destroyMethod = "...") does the same for third-party classes. For code that must run after startup, ApplicationRunner and CommandLineRunner are common. Spring wraps some beans in proxies (transactions, security, caching, async). A call from one method to another inside the same class bypasses the proxy, so @Transactional or @Cacheable on the second method will not apply (the transactions lesson returns to this).
Inspecting and testing
- Set
logging.level.org.springframework=DEBUGor use the Actuatorbeansendpoint to see beans. - Use
@SpringBootTestto start the full context in tests, and@MockitoBeanto replace a bean with a mock (Boot 4 removed@MockBean). - For a plain unit test of a service, skip Spring and construct it with a fake.
Common mistakes
- Field injection with
@Autowired. - Stateful singleton beans that mix up data between requests.
- Putting code outside the scanned packages and wondering why a bean is missing.
- Creating objects with
newinside a bean that should have been injected (new OrderService()gets no dependencies). - Circular dependencies (A needs B needs A); redesign with a third class or events.
- Self-invocation that skips the proxy.
Try it yourself
- Create a Spring Boot project (start.spring.io, Java 21, Maven) and write
OrderRepositoryandOrderServicewith constructor injection. - Add two
PaymentGatewayimplementations and resolve the ambiguity with@Primary, then with@Qualifier. - Add a
@Beanmethod for aClockand inject it into a service so a test can pass a fixed clock. - Print the bean names from
ApplicationContextwith aCommandLineRunner.
Check yourself
What is a Spring bean?
An object whose creation, wiring and lifecycle are managed by the Spring container.
Why is constructor injection preferred over field injection?
It makes dependencies explicit and required, allows final fields, and lets you create the object in plain tests without Spring.
What is the default bean scope and what does it imply?
singleton: one shared instance per container, so the bean must be stateless or thread-safe.
What happens if two beans match an injection point?
Spring fails with NoUniqueBeanDefinitionException unless you mark one @Primary, choose with @Qualifier, or inject a collection.
Interview questions
What is Inversion of Control and Dependency Injection in Spring?
IoC means the framework controls object creation and wiring instead of your code; DI is the way it does it, by supplying each object's dependencies, usually through constructors.
What is the difference between @Component, @Service and @Repository?
All are stereotypes that register a bean through component scanning. @Service marks business logic, and @Repository marks data access and enables persistence exception translation.
How does Spring resolve circular dependencies?
With constructor injection it fails at startup, which is a signal to redesign; setter or field injection of singletons can be resolved with early references, but modern Spring Boot disallows circular references by default.
Summary
- The container creates and wires beans; you declare them with stereotypes or
@Beanmethods. - Use constructor injection,
finalfields and interfaces; resolve ambiguity with@Primaryor@Qualifier. - Beans are singletons by default and must be stateless; scopes and lifecycle callbacks are available.
- Beware proxies and self-invocation.
Going deeper
- Spring Framework: The IoC container: beans, scopes and lifecycle.
- Dependency injection in Spring: constructor versus setter injection.
- Spring Boot: Structuring your code: package layout and component scanning.
- Spring Framework: Annotation-based container configuration:
@Autowired,@Qualifierand@Primary.
See how much of this you can explain
A free mock interview asks you new questions on Spring Boot, REST and JPA for Java Full Stack Developer and scores every answer, with what to fix.