Business logic in services means putting the main rules and decisions of your app in special parts called services. This keeps your code clean and easy to change.
Business logic in services in Spring Boot
Start learning this pattern below
Jump into concepts and practice - no test required
public class SomeService { // Business logic methods public ReturnType methodName(Parameters) { // rules and decisions here } }
Services are usually marked with @Service annotation in Spring Boot.
Services are called by controllers or other parts of the app to perform tasks.
@Service public class OrderService { public double calculateTotalPrice(Order order) { double total = 0; for (Item item : order.getItems()) { total += item.getPrice() * item.getQuantity(); } return total; } }
@Service public class UserService { public boolean canUserAccessFeature(User user) { return user.isActive() && user.getRole().equals("ADMIN"); } }
This example shows a CalculatorService with business logic for adding and multiplying numbers. The CalculatorController calls this service to handle web requests. This keeps the logic separate from the web code.
package com.example.demo.service; import org.springframework.stereotype.Service; @Service public class CalculatorService { public int add(int a, int b) { return a + b; } public int multiply(int a, int b) { return a * b; } } package com.example.demo.controller; import com.example.demo.service.CalculatorService; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class CalculatorController { private final CalculatorService calculatorService; public CalculatorController(CalculatorService calculatorService) { this.calculatorService = calculatorService; } @GetMapping("/add") public int add(@RequestParam int a, @RequestParam int b) { return calculatorService.add(a, b); } @GetMapping("/multiply") public int multiply(@RequestParam int a, @RequestParam int b) { return calculatorService.multiply(a, b); } }
Keep business logic in services to make your app easier to test and maintain.
Controllers should only handle web requests and responses, not complex logic.
Use dependency injection to get service instances in controllers.
Business logic belongs in services, not controllers or repositories.
Services help keep code organized and reusable.
Spring Boot uses @Service to mark service classes.
Practice
Solution
Step 1: Understand Spring Boot layering
Controllers handle HTTP requests, repositories handle data access, and services contain business logic.Step 2: Identify the correct annotation for business logic
The@Serviceannotation marks classes that hold business logic in Spring Boot.Final Answer:
Inside a class annotated with @Service -> Option AQuick Check:
Business logic = @Service class [OK]
- Putting business logic in controllers
- Adding logic inside repository interfaces
- Mixing business logic in the main application class
Solution
Step 1: Recognize the annotation for service classes
Spring Boot uses@Serviceto mark service classes that contain business logic.Step 2: Check the options for correct annotation
Only @Service public class UserService {} uses@Servicecorrectly on the class declaration.Final Answer:
@Service public class UserService {} -> Option AQuick Check:
Service class = @Service annotation [OK]
- Using @Repository or @Controller instead of @Service
- Forgetting to add any annotation
- Placing @Service on interfaces instead of classes
calculateDiscount(150) is called?public class DiscountService {
public int calculateDiscount(int price) {
if (price > 100) {
return price * 20 / 100;
} else {
return price * 10 / 100;
}
}
}Solution
Step 1: Check the input value and condition
The input price is 150, which is greater than 100, so the first branch applies.Step 2: Calculate the discount
Discount = 150 * 20 / 100 = 30, but since integer division is used, it remains 30.Final Answer:
30 -> Option BQuick Check:
Price > 100 -> 20% discount = 30 [OK]
- Choosing 20 thinking it's the percentage, not the amount
- Confusing the else branch discount
- Ignoring integer division effects
@Service
public class OrderService {
@Autowired
private OrderRepository orderRepository;
public void saveOrder(Order order) {
orderRepository.save(order)
}
}Solution
Step 1: Review the method syntax
The lineorderRepository.save(order)is missing a semicolon at the end.Step 2: Validate other parts
Autowired is correct, service classes don't need to extend base classes, and void return is allowed.Final Answer:
Missing semicolon after orderRepository.save(order) -> Option CQuick Check:
Missing semicolon = syntax error [OK]
- Thinking @Autowired is wrong here
- Assuming service classes must extend something
- Believing void methods must return a value
public class PricingService {
private final DiscountService discountService;
private final TaxService taxService;
public PricingService(DiscountService discountService, TaxService taxService) {
this.discountService = discountService;
this.taxService = taxService;
}
public double calculateFinalPrice(double price) {
// Fill in logic here
}
}Solution
Step 1: Understand separation of concerns
Business logic should be inside service classes, not controllers, repositories, or main class.Step 2: Use existing services inside PricingService
Calling discountService and taxService methods inside calculateFinalPrice keeps logic modular and reusable.Final Answer:
Implement calculateFinalPrice to call discountService and taxService methods, then combine results -> Option DQuick Check:
Business logic in services, reuse other services [OK]
- Putting logic in controller or repository layers
- Mixing logic in main application class
- Duplicating discount and tax logic outside services
