Spring Boot interview questions (with answers)
17 min readUpdated
Almost every Java backend role asks about Spring Boot. These questions cover what interviewers ask most, from dependency injection and auto-configuration to REST controllers, transactions and security, with short code samples where they help.
Spring and Spring Boot basics
1. What is the difference between Spring and Spring Boot?
Spring is the framework: dependency injection, web MVC, data access, security. Spring Boot sits on top and removes the setup: starter dependencies, auto-configuration, an embedded server and sensible defaults, so an app runs with main() and almost no configuration.
2. What are inversion of control and dependency injection?
Inversion of control: the framework creates and wires your objects instead of your code calling new. Dependency injection is how it does it: a class declares what it needs (usually as constructor parameters) and Spring passes the right objects in.
3. What is a Spring bean?
An object created and managed by the Spring container (the ApplicationContext). Classes marked @Component, @Service, @Repository or @RestController, and objects returned by @Bean methods, become beans.
4. Which type of injection is best?
Constructor injection: dependencies are final, the object is never half-built, and tests can pass mocks without Spring. With a single constructor, @Autowired is not even needed.
@Service
public class OrderService {
private final OrderRepository orders;
private final PaymentClient payments;
// Spring passes both beans in; no @Autowired needed with one constructor
public OrderService(OrderRepository orders, PaymentClient payments) {
this.orders = orders;
this.payments = payments;
}
}5. What is the difference between @Component, @Service, @Repository and @Controller?
All make a class a bean. The names show the layer: @Service for business logic, @Repository for data access (it also translates database exceptions), @Controller/@RestController for web endpoints, @Component for anything else.
6. What does @SpringBootApplication do?
It combines three annotations: @Configuration (the class can define beans), @EnableAutoConfiguration (turn on auto-configuration) and @ComponentScan (find beans in this package and its sub-packages).
7. What is auto-configuration?
Spring Boot looks at what is on the classpath and what you have configured, then creates beans you would otherwise write by hand. Add the JPA starter and a MySQL driver, set a URL, and a DataSource and EntityManager appear. Your own beans always win.
8. What are starters?
Dependency bundles such as spring-boot-starter-web or spring-boot-starter-data-jpa that bring in everything a feature needs with compatible versions, so you add one dependency instead of ten.
9. What are bean scopes?
singleton (default, one instance per container), prototype (a new instance every time it is requested), and in web apps request and session. Singletons must therefore be stateless or thread safe.
10. What happens if two beans of the same type exist?
Spring cannot choose and fails at startup with NoUniqueBeanDefinitionException. Mark one with @Primary, or pick one at the injection point with @Qualifier("name").
REST APIs
11. What is the difference between @Controller and @RestController?
@RestController = @Controller + @ResponseBody: return values are written straight to the response body as JSON instead of being treated as view names.
12. What is the difference between @PathVariable and @RequestParam?
@PathVariable reads part of the path, /products/{id}. @RequestParam reads the query string, /products?category=books&page=2. Use the path for identity, query parameters for filtering, sorting and paging.
@RestController
@RequestMapping("/api/products")
public class ProductController {
private final ProductService service;
public ProductController(ProductService service) { this.service = service; }
@GetMapping("/{id}")
public ProductResponse get(@PathVariable long id) {
return service.find(id);
}
@GetMapping
public List<ProductResponse> list(@RequestParam(defaultValue = "0") int page) {
return service.list(page);
}
@PostMapping
public ResponseEntity<ProductResponse> create(@Valid @RequestBody CreateProductRequest body) {
ProductResponse created = service.create(body);
return ResponseEntity.created(URI.create("/api/products/" + created.id())).body(created);
}
}13. What does @RequestBody do?
It turns the JSON body of the request into a Java object using Jackson. Combine it with @Valid so Bean Validation checks the fields before your code runs.
14. How do you return the right HTTP status code?
Return a ResponseEntity (ResponseEntity.created(...), ResponseEntity.notFound().build()), or annotate the method with @ResponseStatus. Use 201 for create, 204 for delete with no body, 400 for bad input and 404 for not found.
15. How do you validate request data?
Put Bean Validation annotations on the request class (@NotBlank, @Email, @Min, @Size) and @Valid on the parameter. Invalid input then fails with MethodArgumentNotValidException, which you turn into a clean 400 response.
16. How do you handle exceptions globally?
Write a @RestControllerAdvice class with @ExceptionHandler methods. Each maps an exception (for example ProductNotFoundException) to a status code and a consistent error body, so controllers stay free of try-catch.
17. Why use DTOs instead of returning entities?
A DTO exposes only what the client should see, keeps the API stable when the database changes, and avoids leaking fields such as password hashes or triggering lazy-loading errors during JSON conversion.
Configuration
18. What is the difference between application.properties and application.yml?
Same settings, different format: properties are flat key=value lines, YAML is nested and shorter for grouped settings. Use one style in a project.
19. What are profiles?
Named sets of configuration such as dev, test and prod, in files like application-prod.yml. Activate one with spring.profiles.active, for example from an environment variable.
20. How do you read configuration values?
@Value("${app.page-size}") for a single value, or better, a @ConfigurationProperties(prefix = "app") class (often a record) that groups related settings and can be validated.
21. How should secrets such as database passwords be configured?
Never in the code or in Git. Read them from environment variables or a secrets manager: spring.datasource.password=${DB_PASSWORD}.
22. What is Spring Boot Actuator?
A starter that adds production endpoints such as /actuator/health and /actuator/metrics. Load balancers use the health endpoint to check whether an instance is up. Expose only what you need.
Data and transactions
23. What is the difference between JPA, Hibernate and Spring Data JPA?
JPA is the specification (annotations and the EntityManager API). Hibernate is the most used implementation. Spring Data JPA sits on top and generates repository code from interfaces such as JpaRepository<Product, Long>.
24. How do derived query methods work?
Spring Data reads the method name and writes the query: findByCategoryAndPriceLessThan(String category, BigDecimal max). For anything complex, use @Query with JPQL or native SQL.
25. What does @Transactional do?
It runs the method in a database transaction: commit if it finishes normally, roll back on a RuntimeException (checked exceptions do not roll back by default). Put it on service methods that change data.
26. Why does @Transactional sometimes not work?
It works through a proxy, so it is ignored on private methods and on calls from another method in the same class (self-invocation). Call the method through another bean, or move it.
27. What is the N+1 query problem?
Loading a list of N entities runs one query, then each lazy relationship access runs another, N more. Fix it with a fetch join (JOIN FETCH), an @EntityGraph or a DTO query that loads what the page needs in one go.
Security and testing
28. How does Spring Security work at a high level?
A chain of filters runs before your controllers. They authenticate the request (session, HTTP Basic or a JWT), store the user in the SecurityContext and check authorization rules from your SecurityFilterChain bean.
29. How does JWT authentication work in a Spring Boot API?
The login endpoint checks the password and returns a signed token. The client sends it as Authorization: Bearer <token> on every request; a filter verifies the signature and expiry and sets the user. The server keeps no session.
30. How do you test a Spring Boot application?
Plain JUnit and Mockito for services, @WebMvcTest with MockMvc for controllers, @DataJpaTest for repositories, and @SpringBootTest (often with Testcontainers for a real database) for a few end-to-end tests.
The Spring code above shows the shape of real classes. To run it you need a Spring Boot project with the web, validation and JPA starters; the linked lessons build one step by step.
Frequently asked questions
Is Spring Boot asked in fresher interviews?
For Java backend roles, yes: dependency injection, @RestController, the common annotations and a simple CRUD API. Be ready to explain a Spring Boot project you built.
Which Spring Boot topics matter most for interviews?
Dependency injection and beans, auto-configuration, REST controllers with validation and error handling, Spring Data JPA with transactions, and the basics of Spring Security with JWT.
Do I need to learn Spring before Spring Boot?
No. Learn the core ideas (beans and dependency injection) as part of Spring Boot. The rest of Spring makes sense as you use it.
Learn it step by step
- Spring Framework vs Spring Boot
- Constructor injection and why to prefer it
- Auto-configuration and @SpringBootApplication
- @PathVariable and @RequestParam
- @RestControllerAdvice and @ExceptionHandler
- Self-invocation and other reasons @Transactional is ignored
- The N+1 query problem
- JWT structure: header, payload, signature
- Dependency Injection, Beans and Spring Boot
Practise this, step by step
Short lessons with quizzes, practice and interview questions, from your first program to job-ready.