When I started learning Spring Boot, I kept seeing annotations like @Component, @Service, and @Repository everywhere.

Initially, I thought they were just different ways of telling Spring to create objects. But then I started wondering:

  • Why do we need three different annotations?
  • What exactly is a Spring Bean?
  • Why does Spring create only one object by default?
  • What is the difference between DAO and Repository?
  • How should I organize my Spring Boot application?

These questions might look simple, but understanding them makes a huge difference when you start building real backend applications.

In this post, we'll understand these concepts step by step using a small library application.

Versions used in this post:

  • Java 17
  • Spring Boot 4.2.0
  • Spring Framework 7.1.0

The examples use Java 17-compatible syntax, so the concepts also apply to earlier Spring Boot projects that support Java 17.

Table of contents

  • First understand Spring beans
    • A Java object is not automatically a Spring bean
    • How Spring finds classes with component scanning
  • @Component
  • @Service
  • @Repository
  • DAO and Repository
  • @Scope("prototype")
    • Singleton is the default
    • What prototype actually means
    • The singleton and prototype trap
  • Ideal Layer Structure for a Spring Boot Application
    • The responsibility of each layer
    • A request travels through the layers
    • A practical package structure
  • What else belongs in this foundation
    • Constructor injection
    • Keep services stateless
  • Which one should I use?
  • Common mistakes
  • Quick recap
  • Try it yourself

First understand Spring beans

Before jumping into annotations, let's understand something important.

What exactly is a Spring Bean?

A Spring Bean is simply a Java object that is created, configured, and managed by the Spring IoC container.

Let's understand what that means.

A Java object is not automatically a Spring bean

Consider a normal Java class:

public class BookService { public void getBooks() { System.out.println("Fetching books..."); } } 

We can create its object using the new keyword:

public class Main { public static void main(String[] args) { BookService service = new BookService(); service.getBooks(); } } 

Output:

Fetching books... 

This is a perfectly valid Java program.

But there is one important thing missing.

Spring doesn't know anything about the service object we created using new.

We created that object ourselves, so we are responsible for managing it.

Now imagine an application with hundreds of classes. Some classes depend on other classes, and those classes depend on even more classes.

Managing all these objects manually becomes difficult.

This is where Spring comes in.

What problem does Spring solve?

Spring takes responsibility for creating objects and connecting their dependencies.

This is called Inversion of Control (IoC).

Normally, our code controls object creation. With IoC, we hand that responsibility over to the Spring container.

The container responsible for this is called the IoC container or Spring container.

Two commonly used container interfaces are:

  • BeanFactory: The basic container functionality.
  • ApplicationContext: A more feature-rich container used by most Spring applications.

How Spring finds classes with component scanning

Now the next question is:

How does Spring know which objects it needs to create?

We need to tell Spring which classes should become beans.

One way is through annotations such as @Component, @Service, and @Repository.

Another way is through Java configuration using @Bean.

For now, let's focus on annotations.

When we create a Spring Boot application, we generally have this annotation on our main class:

@SpringBootApplication public class LibraryApplication { public static void main(String[] args) { SpringApplication.run(LibraryApplication.class, args); } } 

One important thing to know is that @SpringBootApplication includes @ComponentScan.

Component scanning means Spring searches specified packages for classes that are eligible to become beans.

By default, Spring Boot scans the package containing the main application class and its subpackages.

For example:

com.example.library | +-- LibraryApplication.java | +-- service | +-- BookService.java | +-- repository | +-- BookRepository.java | +-- support +-- BookFormatter.java 

Spring can discover the annotated classes inside these packages.

Behind the scenes

The process looks something like this:

 SpringApplication.run() | v Spring ApplicationContext | v Component Scanning | v Find annotated component classes | v Register Bean Definitions | v Create Spring Beans | v Inject their dependencies 

Notice something important.

Spring first discovers eligible classes and registers their bean definitions.

A bean definition is essentially a recipe containing information about how a bean should be created.

The actual object is created and managed by the container according to that definition.

Now let's understand the annotations that make this possible.

@Component

@Component is the most generic stereotype annotation provided by Spring.

In simple words:

Use @Component when you want Spring to manage a class, but that class doesn't fit into a more specific application layer.

For example, consider a class responsible for formatting book titles.

import org.springframework.stereotype.Component; @Component public class BookFormatter { public String format(String title) { return "Book: " + title; } } 

That's it!

Spring can now detect this class during component scanning and register it as a bean.

We can inject it into another class using constructor injection.

@Service public class BookService { private final BookFormatter formatter; public BookService(BookFormatter formatter) { this.formatter = formatter; } public String getFormattedTitle(String title) { return formatter.format(title); } } 

Example output:

Book: Effective Java 

The output comes from calling:

System.out.println( bookService.getFormattedTitle("Effective Java") ); 

Why do we need @Component?

Imagine that you have several supporting classes:

  • BookFormatter
  • EmailFormatter
  • DateUtility
  • NotificationHelper

These classes are not necessarily services or repositories.

They are simply supporting components used by different parts of your application.

This is where @Component fits perfectly.

Behind the scenes

Spring recognizes @Component during component scanning and registers the class as a bean definition.

Later, when another bean requests BookFormatter through dependency injection, Spring supplies the managed instance.

One important point:

@Component is also the base stereotype for several other Spring annotations, including @Service and @Repository.

We'll understand why that matters next.

@Service

Now imagine Asha is building a library application.

Users should be able to search for books, borrow books, and return books.

Where should we write the logic for borrowing a book?

Should we write it inside the controller?

Should we put it directly inside the database access class?

Neither is a good choice.

We need a separate place for business logic.

This is where @Service comes in.

@Service identifies a class that belongs to the service layer of an application.

The service layer handles business operations and coordinates different parts of the application.

Example:

import org.springframework.stereotype.Service; @Service public class BookService { public void borrowBook(Long bookId) { System.out.println( "Book borrowed successfully. ID: " + bookId ); } } 

Output:

Book borrowed successfully. ID: 101 

We can also inject other beans into our service.

For example:

@Service public class BookService { private final BookRepository bookRepository; public BookService(BookRepository bookRepository) { this.bookRepository = bookRepository; } public void borrowBook(Long bookId) { bookRepository.findBookById(bookId); System.out.println("Book borrowed successfully."); } } 

Here, BookService coordinates the operation and delegates database access to BookRepository.

Why not use @Component instead?

Technically, you could.

Both annotations make a class eligible for component scanning.

But their meaning is different.

@Component says:

"This is a Spring-managed component."

@Service says:

"This is a Spring-managed component that belongs to the business logic layer."

Using the appropriate annotation makes your application easier to understand and maintain.

Behind the scenes

@Service is itself annotated with @Component.

Conceptually, its relationship looks like this:

 @Component | +------+------+ | | @Service @Repository 

This is why Spring can discover a class annotated with @Service during component scanning.

Spring also recognizes its service-layer role, which can be useful for framework features and application tooling.

@Repository

We have learned that the service layer handles business logic.

But where should we write code that communicates with the database?

For example:

  • Fetch a book by ID.
  • Save a new book.
  • Update book information.
  • Delete a book.

These responsibilities belong to the persistence or data access layer.

This is where @Repository comes in.

@Repository identifies a class that performs data access operations.

Example:

import org.springframework.stereotype.Repository; import java.util.Map; import java.util.Optional; @Repository public class InMemoryBookRepository { private final Map<Long, String> books = Map.of( 1L, "Effective Java", 2L, "Clean Code" ); public Optional<String> findBookById(Long id) { return Optional.ofNullable(books.get(id)); } } 

Output:

Optional[Effective Java] 

The example uses an in-memory Map instead of an actual database so that we can focus on the responsibility of the repository.

Later, we'll replace this implementation with JDBC and Spring Data JPA.

But wait, there is something special about @Repository.

Spring provides an additional feature called exception translation.

Different persistence technologies can produce different types of database-related exceptions.

Spring can translate supported persistence exceptions into its common DataAccessException hierarchy.

This provides a consistent way of handling data access failures.

For example, instead of your service layer needing to understand every database provider's exception type, it can work with Spring's data access exception abstraction.

However, this doesn't mean every exception thrown inside a repository is automatically translated.

The exception translation infrastructure works with supported persistence exceptions.

Behind the scenes

@Repository is also a specialization of @Component.

Therefore, Spring discovers it during component scanning.

It can additionally serve as a marker for Spring's persistence exception translation infrastructure.

DAO and Repository

While learning Spring Boot, you will frequently encounter two terms:

  1. DAO
  2. Repository

Are they the same?

Not exactly, although people sometimes use these terms interchangeably.

Let's understand the difference.

What is DAO?

DAO stands for Data Access Object.

It is a design pattern used to separate database-related operations from the rest of the application.

For example:

public interface BookDao { Optional<String> findBookById(Long id); void saveBook(String title); void deleteBook(Long id); } 

The DAO provides methods for interacting with the data source.

Its implementation might use JDBC, SQL, or another persistence technology.

The main goal is to prevent database access logic from spreading across the application.

What is Repository?

A Repository is a pattern that provides a collection-like abstraction for accessing domain objects.

Think about a library.

You don't necessarily care how the application retrieves a book from the database.

You simply want to perform operations such as:

  • Find a book.
  • Save a book.
  • Delete a book.
  • Find all books.

A repository provides this kind of abstraction.

For example:

public interface BookRepository { Optional<Book> findById(Long id); Book save(Book book); void deleteById(Long id); List<Book> findAll(); } 

Here, the caller works with books rather than worrying about SQL statements or database connections.

What is the actual difference?

The distinction is mostly about the abstraction and design perspective.

DAO generally focuses on isolating data access operations and persistence technology.

Repository generally focuses on providing domain-oriented access to objects.

In real Spring applications, the two terms often overlap.

For example, Spring developers commonly call a class BookRepository even when it performs traditional DAO-style database operations.

Also remember that @Repository is an annotation, while DAO and Repository are architectural patterns or abstractions.

They are not competing annotations.

A useful distinction for later:

Spring Data JPA provides a Repository abstraction and automatically creates implementations for supported repository interfaces.

We will explore that in Part 3.

@Scope("prototype")

Now let's understand something interesting about Spring beans.

When Spring creates a bean, does it always create a new object whenever we request it?

No!

By default, Spring uses singleton scope.

But sometimes we need a new object every time we request a bean.

This is where bean scopes become important.

A bean scope determines how Spring manages the instances created from a bean definition.

Singleton is the default

Singleton is the default scope in Spring.

It means Spring maintains one shared bean instance per bean definition inside a particular Spring container.

Consider this class:

import org.springframework.stereotype.Component; @Component public class BookFormatter { public String format(String title) { return "Book: " + title; } } 

Now suppose we request this bean twice:

BookFormatter first = context.getBean(BookFormatter.class); BookFormatter second = context.getBean(BookFormatter.class); System.out.println(first == second); 

Output:

true 

Why?

Because both references point to the same Spring-managed object.

Behind the scenes

 Spring Container | v BookFormatter Bean | +------+------+ | | v v first second \ / \ / Same Object 

Notice that singleton in Spring does not mean a globally unique object across the entire JVM.

It means one instance per bean definition per Spring container.

What prototype actually means

Now imagine that we are generating reports.

Each report operation needs a separate ReportDraft object containing its own temporary state.

Using the same object repeatedly could cause unwanted state to be shared.

We can use prototype scope.

@Scope("prototype") tells Spring to create a new bean instance every time that bean is requested from the container.

Example:

import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; @Component @Scope("prototype") public class ReportDraft { public ReportDraft() { System.out.println("New ReportDraft created"); } } 

Now request this bean twice:

ReportDraft first = context.getBean(ReportDraft.class); ReportDraft second = context.getBean(ReportDraft.class); System.out.println(first == second); 

Output:

New ReportDraft created New ReportDraft created false 

Why is the output false?

Because Spring created two separate objects.

The first and second references point to different instances.

Behind the scenes

 Spring Container | v ReportDraft Bean | +------+------+ | | v v New Object 1 New Object 2 | | first second 

The same bean definition acts as a recipe for creating multiple objects.

A small but important point:

You can also write the scope using the Spring constant:

@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) 

This avoids manually typing the scope name.

Does prototype mean one object per HTTP request?

No.

Prototype means one new instance per bean request or dependency resolution.

Spring also provides web-specific scopes such as request and session, which have different lifecycles.

The singleton and prototype trap

There is one behaviour that surprises many beginners.

Suppose we have a singleton service that depends on a prototype bean.

@Component @Scope("prototype") public class ReportDraft { } 

Now inject it directly into a service:

@Service public class ReportService { private final ReportDraft reportDraft; public ReportService(ReportDraft reportDraft) { this.reportDraft = reportDraft; } } 

The service is singleton by default.

The ReportDraft dependency is resolved when Spring creates the service.

That means the service receives one prototype instance during its own creation.

Even when you call different methods on the service, the same injected reportDraft reference is used.

This is not what some developers expect.

How do we get a new prototype instance whenever we need one?

Use ObjectProvider.

import org.springframework.beans.factory.ObjectProvider; import org.springframework.stereotype.Service; @Service public class ReportService { private final ObjectProvider<ReportDraft> reportDraftProvider; public ReportService( ObjectProvider<ReportDraft> reportDraftProvider ) { this.reportDraftProvider = reportDraftProvider; } public ReportDraft createDraft() { return reportDraftProvider.getObject(); } } 

Now we can request a fresh instance whenever needed:

ReportDraft first = reportService.createDraft(); ReportDraft second = reportService.createDraft(); System.out.println(first == second); 

Output:

false 

Every call to getObject() asks the Spring container for another prototype instance.

Behind the scenes

 Singleton ReportService | v ObjectProvider<ReportDraft> | +------+------+ | | v v getObject() getObject() | | v v ReportDraft ReportDraft Object 1 Object 2 

One more important lifecycle detail:

Spring initializes prototype beans, but it does not manage their complete destruction lifecycle.

For example, Spring does not automatically invoke configured destruction callbacks for prototype instances.

The application using those objects is responsible for cleaning up resources they hold.

This is another reason why prototype scope should be used thoughtfully.

Ideal Layer Structure for a Spring Boot Application

So far, we have learned about components, services, repositories, and bean scopes.

Now let's put everything together.

Suppose Asha is building a library management system.

The application needs to support:

  • Registering books.
  • Fetching books.
  • Borrowing books.
  • Returning books.
  • Deleting books.

We could write everything inside one class.

But imagine maintaining that class after adding 50 more features.

It would quickly become difficult to understand and modify.

Instead, we divide our application into layers.

This is commonly called Layered Architecture.

The idea is simple:

Each layer should have a specific responsibility.

The responsibility of each layer

A typical Spring Boot backend application contains these layers:

1. Controller Layer

The controller handles incoming HTTP requests.

Its responsibilities include:

  • Receiving requests.
  • Reading request parameters and request bodies.
  • Validating request input.
  • Calling the appropriate service.
  • Returning an HTTP response.

Common annotations:

  • @Controller
  • @RestController
  • @RequestMapping
  • @GetMapping
  • @PostMapping

2. Service Layer

The service layer contains business logic.

Its responsibilities include:

  • Executing business rules.
  • Coordinating multiple repositories.
  • Validating business conditions.
  • Managing application operations.
  • Defining transaction boundaries where appropriate.

Common annotation:

  • @Service

3. Repository Layer

The repository layer handles persistence.

Its responsibilities include:

  • Saving records.
  • Fetching records.
  • Updating records.
  • Deleting records.
  • Executing database queries.

Common annotation:

  • @Repository

4. Entity Layer

Entities represent objects that are mapped to database tables when using JPA.

For example, a Book entity might contain:

public class Book { private Long id; private String title; private String author; } 

In a JPA application, we will add the appropriate persistence annotations.

5. DTO Layer

DTO stands for Data Transfer Object.

DTOs are used to transfer data between different application boundaries.

For example, we might return a BookResponse containing only the book ID and title instead of exposing every field of the database entity.

6. Configuration Layer

This package contains application configuration.

For example:

  • Database configuration.
  • Security configuration.
  • Bean configuration.
  • External service configuration.

A request travels through the layers

Let's understand the complete flow.

Suppose Ravi sends this request:

GET /api/books/101 

How does the request travel through our application?

 CLIENT | | HTTP Request v +------------------+ | CONTROLLER | | | | Receives Request | +------------------+ | | Calls Service v +------------------+ | SERVICE | | | | Business Logic | +------------------+ | | Calls Repository v +------------------+ | REPOSITORY | | | | Database Access | +------------------+ | | SQL / Persistence v +------------------+ | DATABASE | +------------------+ | | Query Result v +------------------+ | REPOSITORY | +------------------+ | v +------------------+ | SERVICE | +------------------+ | v +------------------+ | CONTROLLER | +------------------+ | | HTTP Response v CLIENT 

The important thing to notice is the direction of responsibility.

The controller does not directly communicate with the database.

The service does not need to know how SQL queries are executed.

The repository does not need to know how HTTP requests work.

Each layer focuses on its own responsibility.

This separation makes the application easier to test, maintain, and extend.

A practical package structure

Here is a recommended package structure for a Spring Boot application:

com.example.library | +-- LibraryApplication.java | +-- controller | +-- BookController.java | +-- UserController.java | +-- service | +-- BookService.java | +-- UserService.java | +-- repository | +-- BookRepository.java | +-- UserRepository.java | +-- entity | +-- Book.java | +-- User.java | +-- dto | +-- BookRequest.java | +-- BookResponse.java | +-- config | +-- SecurityConfig.java | +-- exception +-- GlobalExceptionHandler.java +-- BookNotFoundException.java 

Why should we follow this structure?

Imagine tomorrow you want to change your database from MySQL to PostgreSQL.

Ideally, most of your changes should remain inside the persistence-related parts of the application.

Your business logic should not need to know whether you're using MySQL, PostgreSQL, or another supported database.

Similarly, changing the HTTP response format should not require rewriting your database access logic.

This is the main benefit of separating responsibilities.

One important clarification:

This structure is a recommended convention, not something Spring automatically enforces.

Also, don't create additional layers just for the sake of having more packages. Every layer should have a clear responsibility.

What else belongs in this foundation

There are a few related concepts worth understanding before moving to database operations.

Constructor injection

We already used constructor injection in our examples.

But why is it preferred?

Consider this approach:

@Service public class BookService { @Autowired private BookRepository bookRepository; } 

This is called field injection.

It works, but it has some disadvantages:

  • Dependencies are not obvious from the constructor.
  • Testing the class without Spring becomes more difficult.
  • The dependency cannot easily be declared as final.

Instead, prefer constructor injection:

@Service public class BookService { private final BookRepository bookRepository; public BookService(BookRepository bookRepository) { this.bookRepository = bookRepository; } } 

Notice that we don't need @Autowired here.

When a Spring bean has only one constructor, Spring can use that constructor for dependency injection automatically.

This makes dependencies explicit and allows us to use final fields.

Keep services stateless

Remember that singleton is the default bean scope.

That means the same service instance can handle multiple requests.

Now consider this example:

@Service public class BookService { private String currentUser; public void proce...
Source:https://dev.to/mayur_bodhare/spring-beans-explained-component-service-repository-and-scope-3abp