Inversion of Control and Dependency Injection in Spring: One Program, Built Three Ways
A PostService needs a PostRepository. Build it three ways: the service calls new itself (tight coupling), main hands it in through the constructor (DI by hand), and the Spring container does the wiring from a @Configuration recipe.
What you will learn
- Explain a dependency, inversion of control and dependency injection in plain words
- Spot tight coupling when a class calls new on what it needs
- Inject a dependency through the constructor by hand, then let Spring do it
- Read UnsatisfiedDependencyException when a bean is missing
Before you start
- A Plain Spring Project, No Boot
- Java constructors and final fields
Inversion of Control and Dependency Injection are the base of everything Spring does. If these two are clear, the rest of Spring gets much easier. We'll go slowly: first the ideas in plain words, then one small program built three ways, by itself, by hand and by Spring.
What is a dependency?
A car needs an engine; without one it can't drive. The car depends on the engine. In our code, PostService prints blog posts, but it gets them from another class, PostRepository. No repository, no posts. So PostRepository is a dependency of PostService. A dependency is just an object your class needs to do its job.
A repository is the data access part: it knows where the posts live, like a storeroom clerk who knows which shelf an item is on. Today the data is a fixed list; later it'll be a database. The service doesn't care:
package org.studyeasy.spring;
import java.util.List;
// Where the blog posts come from: a fixed list today, a database later
public class PostRepository {
public PostRepository() {
// shows WHO creates it, and when
System.out.println("PostRepository created");
}
public List<String> findAllTitles() {
return List.of("Hello, Spring", "Why Constructor Injection");
}
}
The print in the constructor fires the moment the object is created, so in every version we can see who creates the repository, and when.
Who creates the dependency?
Option one: PostService creates it itself with new PostRepository(). The class is in control, like a new hire who goes out on day one and buys their own laptop. Option two: someone outside creates it and hands it in, like a company that buys the laptop and gives it to the new hire. That flip, the class giving up control of creating what it needs, is Inversion of Control.
How does it reach the class? Through the constructor. The class declares a field and a constructor that takes the dependency; the outside world calls new PostService(repository). Handing it in is Dependency Injection, and doing it through the constructor is constructor injection.
Version 1: the service builds its own repository
package org.studyeasy.spring;
public class Ex01_TightCoupling {
// The problem: this service builds its own repository
static class PostService {
// hard-wired: the service decides which repository it gets
private final PostRepository repository = new PostRepository();
void printPosts() {
for (String title : repository.findAllTitles()) {
System.out.println("- " + title);
}
}
}
public static void main(String[] args) {
PostService service = new PostService(); // no say in it
service.printPosts();
}
}
PostRepository created
- Hello, Spring
- Why Constructor Injection
It works. The problem is the field line: PostService picks its repository and builds it, hard-wired. The caller just says new PostService() and has no say. Want a test repository or a database repository tomorrow? You'd have to edit PostService. That's tight coupling.
Version 2: you do the wiring
The same class, now in its own file, takes its repository in the constructor:
package org.studyeasy.spring;
public class PostService {
private final PostRepository repository; // final: set once
// The repository is handed in - PostService never calls new on it
public PostService(PostRepository repository) {
this.repository = repository;
System.out.println("PostService created");
}
public void printPosts() {
for (String title : repository.findAllTitles()) {
System.out.println("- " + title);
}
}
}
A final field, set once, and no new anywhere. Now main builds the parts:
package org.studyeasy.spring;
public class Ex02_ConstructorInjection {
public static void main(String[] args) {
// Plain Java DI: YOU create the parts and hand them over
PostRepository repository = new PostRepository();
// handed in through the constructor - no framework yet
PostService service = new PostService(repository);
service.printPosts();
}
}
PostRepository created
PostService created
- Hello, Spring
- Why Constructor Injection
The repository is created first, because the service needs it. Want a test repository? Pass another one; PostService doesn't change. And this is already Dependency Injection, in plain Java with no framework. Spring doesn't invent DI; it takes over the wiring.
Version 3: the Spring container does the wiring
Spring needs a recipe that says which objects to make. The container, called the ApplicationContext, reads it, creates the objects, wires them and keeps them ready. Every object it manages is a bean.
package org.studyeasy.spring;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
// A recipe for the container: one method per object it should make
@Configuration
public class BlogConfig {
@Bean
public PostRepository postRepository() {
return new PostRepository();
}
// The parameter: Spring hands in the PostRepository bean above
@Bean
public PostService postService(PostRepository repository) {
return new PostService(repository);
}
}
Each @Bean method makes one bean. Look at the parameter of postService: we never call this method ourselves. Spring passes in the PostRepository bean it already made. Inside, it's still new PostService(repository), still constructor injection; Spring just does the handing.
package org.studyeasy.spring;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Ex03_SpringContainer {
public static void main(String[] args) {
// Start the container from the recipe: it creates every @Bean
try (var context =
new AnnotationConfigApplicationContext(BlogConfig.class)) {
System.out.println("Container ready");
// Ask for the finished object - no new, no wiring here
PostService service = context.getBean(PostService.class);
service.printPosts();
}
}
}
PostRepository created
PostService created
Container ready
- Hello, Spring
- Why Constructor Injection
Both objects exist before "Container ready". Starting the container is what makes them: Spring calls postRepository(), then postService(...) with that bean, and by the time getBean runs, the PostService is sitting there with its repository inside. There's no new in main.
Remove one @Bean
Delete only the @Bean line above postRepository() and run Ex03 again. Now postRepository is a normal method Spring never calls, so no repository bean exists, but postService still needs one. This time the container itself fails while starting, so not even "PostRepository created" or "Container ready" print:
UnsatisfiedDependencyException ... No qualifying bean of type 'org.studyeasy.spring.PostRepository' available
The full message even says where: while creating the bean postService, parameter 0. Spring only injects what it knows how to make. That's a good thing: you hear about the problem at startup, not in the middle of a user's request. Put the @Bean back and it works again.
Three versions, one question: who calls new?
| V1 new inside | V2 by hand | V3 Spring | |
|---|---|---|---|
| Who creates the repository | PostService itself | you, in main | the container |
| Code | new PostRepository() in the class | new PostService(repo) | getBean(PostService.class) |
| Swap the repository | edit PostService | pass another one | change an @Bean |
| Inversion of Control? | no | yes | yes |
| In this course | avoid | yes | yes |
Hand it in, never new it inside. A class asks for what it needs through its constructor, and someone outside, you or Spring, hands it in. Next, let Spring find your classes on its own with component scanning.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
Why Spring in 2026: What the Container Does and What Spring Framework 7 Changed
Spring in one line: a container that creates your classes and hands each one what it needs. Plus the Spring Framework 7 baseline (JDK 17 to 25, Jakarta EE 11, Tomcat 11, JUnit 6), what got better than Spring 6, and a two-line version check.
A Plain Spring Project, No Boot: Your First Bean With spring-context
One dependency, one recipe, one getBean: a Maven project with spring-context 7.0.9, a Blog record, an AppConfig with @Bean, and a main that asks the container for the Blog. Then delete @Bean and meet NoSuchBeanDefinitionException.
Spring Component Scanning: @Component and @ComponentScan Instead of @Bean Methods
Instead of one @Bean method per class, put @Component on EmailNotifier and PostService and @ComponentScan on an empty BlogConfig. Spring walks the package, finds the stickers and builds the beans; main doesn't change.
Spring Autowiring: Spring Fills the Constructor, and When @Autowired Is Needed
PostService asks for an EmailNotifier in its constructor and Spring plugs in the matching bean. With one constructor that's all. Add a second, empty constructor and Spring picks it, the notifier stays null, and only @Autowired fixes the choice.
