1. Constructors
Purpose: Initialize objects when created
Key Features:
Same name as class
No return type
Can be overloaded
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:
Dependency Injection (DI)
Database Repositories
API Clients
Example Service with Data Access:
@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:
Type | Example | Use Case |
---|---|---|
Instance | product.calculateTax() | Object-specific operations |
Static | MathUtils.round(price) | Utility functions |
Abstract | abstract void validate() | Framework hooks |
Default (Interface) | Logger.log("msg") | Interface backward compatibility |
B) Class Types:
Type | Example | Use Case |
---|---|---|
POJO | Product.java | Data containers |
Service | OrderService.java | Business logic |
Repository | ProductRepository.java | Database access |
Controller | ProductController.java | REST endpoint handler |
Configuration | SecurityConfig.java | Spring bean setup |
DTO (Data Transfer Object) | ProductResponse.java | API response structure |
4. Complete Microservice Flow Example
// 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
Client Request:
GET /products/affordable?maxPrice=100
Controller:
Receives HTTP request
Extracts
maxPrice
parameterCalls service method
Service:
Contains business logic
Calls repository for data
Transforms data to DTO
Repository:
Talks to database (e.g., MySQL, PostgreSQL)
Executes SQL query:
SELECT * FROM products WHERE price < 100
Response Journey:
Database → Repository → Service → Controller → HTTP Response
Key Takeaways:
Constructors initialize objects and dependencies
Services get data through:
Injected dependencies (repositories, API clients)
Method parameters
Static utility methods
Method Categories:
Data Access:
repository.findByX()
Business Logic:
service.processOrder()
API Handling:
controller.handleRequest()
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