Difference Between Bean and DTO in Spring Boot

Bean and DTO are terms of classes used in Spring Boot. But they are different from each other like purposes and usages within the Spring Boot application. This topic will help use to explore the difference between Bean and DTO, their annotations, how they’re used in real-world applications, and when to choose one over the other.

Difference Between Bean and DTO in Spring Boot

Bean in Spring Boot

A Spring Bean class’s object is managed by the Spring container.

Example:

@Service

public class EmailService {

    public void sendEmail(String to, String body) {

        System.out.println("Email sent to " + to);

    }

}

DTO

This is a class. It is using for sending or receiving data.

Example:

public class UserDTO {

    private String name;

    private String email;

    public UserDTO() {}

    public UserDTO(String name, String email) {

        this.name = name;

        this.email = email;

    }

    // Getters and Setters

}

Key Difference Between Bean and DTO

FeatureSpring BeanDTO 
PurposeHandles logic, service, or configurationTransfers data across layers or systems
Managed by SpringYes No
AnnotationsUse annotations such as @Component, @Service, etc.None
Includes Business Logic?Yes No
Used InService layer, config classes, data accessAPI request/response, inter-layer communication
Dependency Injection? Yes (@Autowired)No (manually instantiated or mapped)
Framework DependencySpring FrameworkFramework-agnostic

When to Use Bean vs DTO

Use Bean When

  • We are creating a service, repository, or config component.
  • We want Spring to inject it into other components.
  • We need logic execution or task handling.

Use DTO When

  • We are defining a REST API request or response format.
  • We need to transfer structured data between layers.
  • We want to filter or reshape data from entities or beans.

Real-World Example in a Spring Boot App

DTO:

public class ProductDTO {

    private String name;

    private double price;

    // Constructors, Getters, Setters

}

Bean:

@Service

public class ProductService {

    public double applyDiscount(double price) {

        return price * 0.9;

    }

}

Controller using both:

@RestController

@RequestMapping("/products")

public class ProductController {

    @Autowired

    private ProductService productService;

    @PostMapping("/discount")

    public double calculateDiscount(@RequestBody ProductDTO productDTO) {

        return productService.applyDiscount(productDTO.getPrice());

    }

}

Conclusion

In Spring Boot:

  • A Bean is a Spring-managed object responsible for executing logic, providing services, or managing configuration.
  • A DTO is a data carrier, used to structure and transfer data across layers or APIs.

Leave a Comment