In today's dynamic IT industry, strong command over Java Spring Boot is essential for freshers and developers with 0-3 years of experience. Companies seek candidates who can apply theoretical knowledge to practical scenarios, especially in building efficient microservices. This post from itdefined.org offers scenario-based Spring Boot interview questions and answers to help you ace your interviews.
Scenario 1: Core Spring Boot Component Definition
Question:
You need to create a UserService to manage user-related business logic. How would you define this component and ensure it's available for dependency injection within your Spring Boot application?
Answer:
We use the @Service annotation to mark UserService as a Spring component, indicating it holds business logic. Spring's component scanning (enabled by @SpringBootApplication) discovers it. We then use @Autowired to inject it where needed, like into a controller.
// UserService.java
@Service
public class UserService {
public String getUserDetails(Long id) {
return 'User details for ID: ' + id;
}
}
// UserController.java
@RestController
@RequestMapping('/api/users')
public class UserController {
private final UserService userService;
@Autowired
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping('/{id}')
public String getUser(@PathVariable Long id) {
return userService.getUserDetails(id);
}
}
Scenario 2: Building RESTful APIs for Product Management
Question:
Design a RESTful API endpoint to add a new product to an e-commerce system. How do you handle incoming JSON data and return an appropriate response?
Answer:
We'd use @RestController for the class and @PostMapping to map the HTTP POST request. The @RequestBody annotation automatically deserializes incoming JSON into a Java Product object. We return a ResponseEntity with HttpStatus.CREATED (201) on success.
// Product.java (simplified)
public class Product {
private Long id; private String name; private double price;
// Getters, Setters, Constructors
}
// ProductController.java
@RestController
@RequestMapping('/api/products')
public class ProductController {
// Assume ProductService is injected
@Autowired private ProductService productService;
@PostMapping
public ResponseEntity<Product> addProduct(@RequestBody Product product) {
Product savedProduct = productService.save(product); // Assuming productService.save()
return new ResponseEntity<>(savedProduct, HttpStatus.CREATED);
}
}
Scenario 3: Data Persistence with Spring Data JPA & Hibernate
Question:
How do Spring Data JPA and Hibernate simplify storing and retrieving data for your microservice? Illustrate with a simple Product entity and its repository.
Answer:
Spring Data JPA provides an abstraction over JPA providers like Hibernate, eliminating boilerplate code for database operations. We define our data model as an @Entity with an @Id. By extending JpaRepository, Spring Data JPA automatically provides CRUD methods, enabling easy persistence without writing SQL.
// Product.java (JPA Entity)
import javax.persistence.*;
@Entity
public class Product {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private double price;
// Getters, Setters, Constructors
}
// ProductRepository.java
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
// Spring Data JPA provides save(), findById(), etc.
}
// ProductService.java (using the repository)
@Service
public class ProductService {
@Autowired private ProductRepository productRepository;
public Product save(Product product) {
return productRepository.save(product);
}
public Product findById(Long id) {
return productRepository.findById(id).orElse(null);
}
}
Scenario 4: Robust Validation and Exception Handling
Question:
How would you validate incoming product data (e.g., price > 0, name not empty) and handle cases where a client requests a non-existent product ID in your Spring Boot microservice?
Answer:
For data validation, we use Java Bean Validation (e.g., Hibernate Validator) with annotations like @NotBlank and @Min on our Product DTO/entity fields. The @Valid annotation on the @RequestBody triggers this validation. For error handling, a global @ControllerAdvice with @ExceptionHandler methods centralizes the logic. We can catch MethodArgumentNotValidException for validation errors and a custom exception (e.g., ProductNotFoundException) for non-existent resources, returning appropriate HTTP status codes (400 Bad Request, 404 Not Found).
// Product.java (with validation)
import javax.validation.constraints.*;
public class Product {
@NotBlank(message = 'Name is required')
private String name;
@Min(value = 1, message = 'Price must be positive')
private double price;
// ...
}
// ProductController.java (with @Valid)
@RestController
@RequestMapping('/api/products')
public class ProductController {
@PostMapping
public ResponseEntity<Product> addProduct(@Valid @RequestBody Product product) {
// ...
}
}
// GlobalExceptionHandler.java
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import java.util.HashMap;
import java.util.Map;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Map<String, String> handleValidationExceptions(MethodArgumentNotValidException ex) {
Map<String, String> errors = new HashMap<>();
ex.getBindingResult().getFieldErrors().forEach(error ->
errors.put(error.getField(), error.getDefaultMessage()));
return errors;
}
// Custom exception for resource not found
@ResponseStatus(HttpStatus.NOT_FOUND)
public static class ProductNotFoundException extends RuntimeException {
public ProductNotFoundException(String message) { super(message); }
}
@ExceptionHandler(ProductNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public ResponseEntity<String> handleProductNotFound(ProductNotFoundException ex) {
return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
}
}
Conclusion
These scenario-based Java Spring Boot interview questions cover essential skills for building modern microservices, from core component design and RESTful APIs to data persistence with JPA and Hibernate, and robust error handling. Understanding the practical application of these concepts is crucial. Keep practicing, build small projects, and stay updated with the latest Spring Boot features. For more career-boosting insights and training, make sure to follow itdefined.org!