Spring Boot
Spring Boot
Suppose you have two implementations of an interface, and both are marked with @Component.
Spring won’t know which one to inject into a dependent class.
🔹 Syntax
@Autowired
@Qualifier("beanName")
private MyService myService;
✅ Example
1. Define an Interface
public interface PaymentService {
void pay();
}
2. Two Implementations
@Component("paypalService")
public class PaypalService implements PaymentService {
public void pay() {
System.out.println("Paid via PayPal");
}
}
@Component("creditCardService")
public class CreditCardService implements PaymentService {
public void pay() {
System.out.println("Paid via Credit Card");
}
}
3. Injecting with @Qualifier
@Component
public class PaymentProcessor {
@Autowired
@Qualifier("paypalService") // specify which implementation to use
private PaymentService paymentService;
✅ What is @ControllerAdvice?
@ControllerAdvice is a specialized @Component used to define global exception handling,
binding, and model attribute logic.
You can define multiple @ExceptionHandler methods within it to handle different
exceptions.
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(UserNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
@ResponseBody
public ErrorResponse handleUserNotFound(UserNotFoundException ex) {
return new ErrorResponse("USER_NOT_FOUND", ex.getMessage());
}
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public ErrorResponse handleGenericException(Exception ex) {
return new ErrorResponse("INTERNAL_ERROR", "An unexpected error occurred.");
}
}
3. Create a Response Wrapper (Optional)
public class ErrorResponse {
private String code;
private String message;
@GetMapping("/{id}")
public String getUser(@PathVariable int id) {
if (id != 1) {
throw new UserNotFoundException("User with ID " + id + " not found");
}
return "User Found!";
}
}
🟨 Output Example
Response:
json
CopyEdit
{
"code": "USER_NOT_FOUND",
"message": "User with ID 2 not found"
}
Status Code: 404 Not Found
✅ What is AOP in Spring Boot?
AOP (Aspect-Oriented Programming) is a programming paradigm in Spring that allows you to
separate cross-cutting concerns (e.g., logging, security, transactions) from the main business logic.
In Spring Boot, AOP is implemented using Spring AOP, which uses proxies under the hood.
2. Create a Service
@Service
public class UserService {
public String getUser(int id) {
return "User with ID: " + id;
}
}
3. Create an Aspect
@Aspect
@Component
public class LoggingAspect {
@Before("execution(* com.example.demo.service.UserService.*(..))")
public void logBeforeMethod(JoinPoint joinPoint) {
System.out.println("Before method: " + joinPoint.getSignature().getName());
}
@AfterReturning(
pointcut = "execution(* com.example.demo.service.UserService.*(..))",
returning = "result")
public void logAfterReturning(JoinPoint joinPoint, Object result) {
System.out.println("Method " + joinPoint.getSignature().getName() + " returned: " + result);
}
}
@Autowired
private UserService userService;
@GetMapping("/user/{id}")
public String getUser(@PathVariable int id) {
return userService.getUser(id);
}
}
✅ 4. Validation Annotations
Annotation Description
@Valid / @Validated Triggers validation on a method parameter or field.
@NotNull, @Size, @Min, @Max, Bean Validation annotations for field-level validation (from
@Email etc. javax.validation).
✅ 9. Spring Security
Annotation Description
@EnableWebSecurity Enables Spring Security configuration.
@PreAuthorize, @PostAuthorize Method-level authorization using SpEL.
@Secured Specifies security roles for methods.
@WithMockUser Used in unit testing to mock a user.
✅ 2. Filtering Elements
✅ 3. Mapping Elements
✅ 4. Sorting Elements
✅ 5. Custom Sorting
✅ 7. Distinct Elements
✅ 14. Group By
✅ 15. Partition By
✅ 16. FlatMap
🔹 @Cacheable Example
@Service
public class ProductService {
@Cacheable("products")
public Product getProductById(String id) {
simulateSlowService(); // Simulate DB call
return new Product(id, "Product " + id);
}
}
📌 Explanation:
First call with a new id will fetch and cache result.
Subsequent calls with the same id will return cached result.
🔹 @CachePut Example
@CachePut(value = "products", key = "#product.id")
public Product updateProduct(Product product) {
return productRepository.save(product);
}
📌 Updates both the database and cache entry.
🔹 @CacheEvict Example
@CacheEvict(value = "products", key = "#id")
public void deleteProduct(String id) {
productRepository.deleteById(id);
}
📌 Removes cache entry after deletion.
🧠 Interview-Focused Summary
Concept Notes
🧾 5. Token Validation
The application validates the token:
o Signature check (to ensure it's unaltered).
o Expiration check (token expiry date/time).
o Issuer/audience (optional, to verify it came from trusted SSO server).
🔐 7. Access Control
Spring Security uses extracted roles to:
o Allow access to the requested resource.
o Deny access (403 Forbidden) if roles are insufficient.
✅ Design Pattern in Microservices
Pattern Purpose