Java Microservices: Core Concepts Explained with Examples

 

1. Constructors

Purpose: Initialize objects when created
Key Features:

  • Same name as class

  • No return type

  • Can be overloaded

java
public class ProductService {
    private ProductRepository repo;
    
    // Constructor: Initializes dependencies
    public ProductService(ProductRepository repo) {
        this.repo = repo;  // Dependency Injection
    }
    
    // Overloaded constructor (default repo)
    public ProductService() {
        this.repo = new DefaultProductRepository();
    }
}

2. Getting Data in Services

Common Methods:

  1. Dependency Injection (DI)

  2. Database Repositories

  3. API Clients

Example Service with Data Access:
java
@Service  // Spring stereotype annotation
public class OrderService {
    
    // 1. Dependency Injection
    @Autowired
    private OrderRepository orderRepo;  // Database access
    
    @Autowired
    private PaymentClient paymentClient;  // External service
    
    // 2. Constructor injection (recommended)
    public OrderService(OrderRepository orderRepo, 
                       PaymentClient paymentClient) {
        this.orderRepo = orderRepo;
        this.paymentClient = paymentClient;
    }

    // 3. Business method using data
    public Order processOrder(OrderRequest request) {
        // Get data from database
        Order order = orderRepo.save(new Order(request));
        
        // Get data from external service
        PaymentStatus status = paymentClient.charge(order);
        
        order.setStatus(status);
        return orderRepo.save(order);
    }
}

**3. Methods & Classes in Java

A) Method Types:
TypeExampleUse Case
Instanceproduct.calculateTax()Object-specific operations
StaticMathUtils.round(price)Utility functions
Abstractabstract void validate()Framework hooks
Default (Interface)Logger.log("msg")Interface backward compatibility
B) Class Types:
TypeExampleUse Case
POJOProduct.javaData containers
ServiceOrderService.javaBusiness logic
RepositoryProductRepository.javaDatabase access
ControllerProductController.javaREST endpoint handler
ConfigurationSecurityConfig.javaSpring bean setup
DTO (Data Transfer Object)ProductResponse.javaAPI response structure

4. Complete Microservice Flow Example

java
// 1. DTO Class (Data Transfer Object)
public record ProductResponse(Long id, String name, double price) {}

// 2. Repository Interface (Data Access)
public interface ProductRepository extends JpaRepository<Product, Long> {
    List<Product> findByPriceLessThan(double maxPrice);  // Spring Data method
}

// 3. Service Class (Business Logic)
@Service
public class ProductService {
    private final ProductRepository repo;

    public ProductService(ProductRepository repo) {
        this.repo = repo;
    }

    // Business method
    public List<ProductResponse> getAffordableProducts(double maxPrice) {
        return repo.findByPriceLessThan(maxPrice)
                  .stream()
                  .map(p -> new ProductResponse(p.getId(), p.getName(), p.getPrice()))
                  .toList();
    }
}

// 4. Controller Class (REST API)
@RestController
@RequestMapping("/products")
public class ProductController {
    private final ProductService service;

    public ProductController(ProductService service) {
        this.service = service;
    }

    @GetMapping("/affordable")
    public ResponseEntity<List<ProductResponse>> getAffordable(
            @RequestParam double maxPrice) {
        return ResponseEntity.ok(service.getAffordableProducts(maxPrice));
    }
}

5. Data Flow in Microservices

  1. Client Request:
    GET /products/affordable?maxPrice=100

  2. Controller:

    • Receives HTTP request

    • Extracts maxPrice parameter

    • Calls service method

  3. Service:

    • Contains business logic

    • Calls repository for data

    • Transforms data to DTO

  4. Repository:

    • Talks to database (e.g., MySQL, PostgreSQL)

    • Executes SQL query:

      sql
      SELECT * FROM products WHERE price < 100
  5. Response Journey:
    Database → Repository → Service → Controller → HTTP Response


Key Takeaways:

  1. Constructors initialize objects and dependencies

  2. Services get data through:

    • Injected dependencies (repositories, API clients)

    • Method parameters

    • Static utility methods

  3. Method Categories:

    • Data Access: repository.findByX()

    • Business Logic: service.processOrder()

    • API Handling: controller.handleRequest()

  4. Class Responsibilities:

    • Controller: Handle HTTP requests/responses

    • Service: Implement business rules

    • Repository: Manage database operations

    • DTO: Define data structure for API communication

No comments:

Post a Comment

Java Microservices: Core Concepts Explained with Examples

  1. Constructors Purpose:  Initialize objects when created Key Features: Same name as class No return type Can be overloaded java public c...

Best for you