Quick answer: These 48 Spring Boot interview questions and answers cover what is asked most in Java back-end developer and full-stack developer interviews: Spring Boot basics, dependency injection and beans, REST APIs, Spring Data JPA, configuration and Actuator, security and microservices, and testing and deployment. Key answers include short code examples.
Read each answer, then close the page and explain it aloud in two or three sentences. That is exactly what interviewers check.
Contents
- Spring and Spring Boot Basics
- Dependency Injection and Beans
- REST APIs with Spring Boot
- Spring Data JPA
- Configuration, Profiles and Actuator
- Security and Microservices
- Testing and Deployment
- How to prepare
- FAQs
1. Spring and Spring Boot Basics Interview Questions
Q1. What is Spring Boot?
Spring Boot is a framework built on top of Spring that makes it quick to create stand-alone, production-ready Java applications. It provides auto-configuration, starter dependencies and an embedded server such as Tomcat, so you can run an application with java -jar and very little configuration.
Q2. What is the difference between Spring and Spring Boot?
Spring is the core framework for dependency injection, MVC, data access and more, but it needs a lot of manual configuration. Spring Boot adds auto-configuration, starters, an embedded server, production features through Actuator, and sensible defaults, so you write far less setup code.
Q3. What are the main features of Spring Boot?
Auto-configuration, starter dependencies, embedded servers (Tomcat, Jetty, Undertow), externalised configuration with application.properties or YAML, Spring Boot Actuator for monitoring, and easy packaging as an executable JAR.
Q4. What does @SpringBootApplication do?
It is a convenience annotation that combines @Configuration (the class defines beans), @EnableAutoConfiguration (turns on auto-configuration) and @ComponentScan (scans the package and sub-packages for components).
@SpringBootApplication
public class ShopApplication {
public static void main(String[] args) {
SpringApplication.run(ShopApplication.class, args);
}
}Q5. What is auto-configuration?
Auto-configuration automatically creates beans based on the libraries on the classpath and your properties. For example, if spring-boot-starter-data-jpa and a database driver are present, Spring Boot configures a DataSource and an EntityManagerFactory for you. You can override any of it with your own beans.
Q6. What are Spring Boot starters?
Starters are dependency bundles that bring in everything needed for a feature, with compatible versions. Examples: spring-boot-starter-web for REST APIs, spring-boot-starter-data-jpa for databases, spring-boot-starter-security and spring-boot-starter-test.
Q7. What is the embedded server in Spring Boot?
Spring Boot packages a web server, Tomcat by default, inside the application JAR, so you do not deploy a WAR file to an external server. You can switch to Jetty or Undertow by changing the starter dependency.
Q8. How do you change the default port?
Set server.port in application.properties (server.port=8081) or application.yml, or pass it on the command line with –server.port=8081.
2. Dependency Injection and Beans Interview Questions
Q9. What is dependency injection?
Dependency injection means an object receives the objects it depends on from outside instead of creating them itself. Spring's IoC (Inversion of Control) container creates the objects and injects them, which makes code loosely coupled and easy to test.
Q10. What are the types of dependency injection in Spring?
Constructor injection, setter injection and field injection (@Autowired on a field). Constructor injection is recommended because dependencies are required, can be final, and the class is easy to test.
@Service
public class OrderService {
private final OrderRepository repo;
public OrderService(OrderRepository repo) { // constructor injection
this.repo = repo;
}
}Q11. What is a Spring bean?
A bean is an object created, configured and managed by the Spring container. Classes marked with @Component, @Service, @Repository or @Controller, or returned from @Bean methods, become beans.
Q12. What is the difference between @Component, @Service, @Repository and @Controller?
All mark a class as a Spring bean. @Service is for business logic, @Repository is for data access and also translates database exceptions, @Controller handles web requests, and @Component is the generic version. They make the code's layers clear.
Q13. What is the difference between @Bean and @Component?
@Component is placed on a class so Spring detects it during scanning. @Bean is placed on a method inside a @Configuration class and returns an object; it is used for third-party classes you cannot annotate.
Q14. What are bean scopes?
singleton (one instance per container, the default), prototype (a new instance each time), and for web apps request, session and application scopes.
Q15. What is the use of @Qualifier and @Primary?
When several beans of the same type exist, @Primary marks the default one to inject, and @Qualifier("name") chooses a specific bean at the injection point.
Q16. What is the bean life cycle?
Spring creates the bean, injects dependencies, calls initialisation callbacks such as @PostConstruct, makes the bean available, and calls destruction callbacks such as @PreDestroy when the container shuts down.
3. REST APIs with Spring Boot Interview Questions
Q17. What is the difference between @Controller and @RestController?
@Controller returns view names for server-side pages. @RestController combines @Controller and @ResponseBody, so return values are written directly to the response, usually as JSON.
Q18. How do you create a REST API in Spring Boot?
Create a class with @RestController, map methods with @GetMapping, @PostMapping, @PutMapping and @DeleteMapping, and return objects or ResponseEntity.
@RestController
@RequestMapping("/api/products")
public class ProductController {
private final ProductService service;
public ProductController(ProductService service) { this.service = service; }
@GetMapping("/{id}")
public ResponseEntity<Product> get(@PathVariable Long id) {
return ResponseEntity.ok(service.findById(id));
}
@PostMapping
public ResponseEntity<Product> create(@Valid @RequestBody Product p) {
return ResponseEntity.status(HttpStatus.CREATED).body(service.save(p));
}
}Q19. What is the difference between @PathVariable and @RequestParam?
@PathVariable reads a value from the URL path, such as /users/10. @RequestParam reads a query parameter, such as /users?page=2.
Q20. What does @RequestBody do?
@RequestBody converts the JSON body of a request into a Java object using Jackson.
Q21. What is ResponseEntity?
ResponseEntity represents the full HTTP response: status code, headers and body. It lets you return 201 Created, 404 Not Found and so on, instead of always 200.
Q22. How do you handle exceptions globally?
Use a class annotated with @RestControllerAdvice and methods annotated with @ExceptionHandler, which convert exceptions into proper error responses for every controller.
@RestControllerAdvice
public class GlobalHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<String> notFound(ResourceNotFoundException e) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(e.getMessage());
}
}Q23. How do you validate request data?
Add spring-boot-starter-validation, put constraints such as @NotNull, @NotBlank, @Email and @Size on fields, and add @Valid before the @RequestBody parameter. Invalid input triggers MethodArgumentNotValidException, which you can handle globally.
Q24. What are the common HTTP methods and status codes in REST?
GET reads, POST creates, PUT replaces, PATCH partially updates and DELETE removes. Common status codes are 200 OK, 201 Created, 204 No Content, 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found and 500 Internal Server Error.
4. Spring Data JPA Interview Questions
Q25. What is Spring Data JPA?
Spring Data JPA simplifies database access on top of JPA and Hibernate. You define repository interfaces, and Spring generates the implementation for common operations and for queries derived from method names.
Q26. What is the difference between CrudRepository and JpaRepository?
CrudRepository provides basic create, read, update and delete methods. JpaRepository extends it (through ListCrudRepository and PagingAndSortingRepository) and adds JPA-specific methods such as flush, saveAll and batch deletes, plus paging and sorting.
Q27. How do derived query methods work?
Spring parses the method name and builds the query, for example findByEmail, findByAgeGreaterThan or findByCityOrderByNameAsc.
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByEmail(String email);
List<User> findByCityAndActiveTrue(String city);
}Q28. How do you write a custom query?
Use @Query with JPQL, or with nativeQuery = true for SQL.
@Query("SELECT u FROM User u WHERE u.salary > :min")
List<User> highEarners(@Param("min") double min);Q29. What is the difference between lazy and eager loading?
Eager loading fetches related entities immediately with the parent. Lazy loading fetches them only when they are first accessed. @OneToMany and @ManyToMany are lazy by default; @ManyToOne and @OneToOne are eager by default.
Q30. What is the N+1 query problem and how do you fix it?
It happens when loading N parent records triggers one extra query per record to load their children. Fix it with JOIN FETCH in JPQL, @EntityGraph, or batch fetching.
Q31. What does @Transactional do?
@Transactional runs a method inside a database transaction: all changes are committed together, or rolled back if a runtime exception occurs. It works through Spring proxies, so calling a @Transactional method from inside the same class bypasses it.
Q32. How do you implement pagination?
Pass a Pageable to the repository method and return a Page, which includes the data and total counts.
Page<Product> page = repo.findAll(PageRequest.of(0, 20, Sort.by("price").descending()));5. Configuration, Profiles and Actuator Interview Questions
Q33. What is the difference between application.properties and application.yml?
Both hold configuration. Properties files use key=value lines; YAML uses an indented hierarchy that is easier to read for nested settings. Use one style consistently.
Q34. What are Spring profiles?
Profiles let you keep separate configuration for environments such as dev, test and prod, in files like application-dev.properties. You activate one with spring.profiles.active=dev.
Q35. How do you read configuration values?
Use @Value("${app.name}") for single values, or @ConfigurationProperties on a class to bind a group of related properties in a type-safe way.
Q36. What is Spring Boot Actuator?
Actuator adds production endpoints for monitoring and management, such as /actuator/health, /actuator/metrics and /actuator/info. Only some endpoints are exposed over HTTP by default, and sensitive ones should be secured.
Q37. What is Spring Boot DevTools?
DevTools speeds up development with automatic restart when code changes, LiveReload, and development-friendly defaults. It is disabled automatically in packaged production applications.
6. Security and Microservices Interview Questions
Q38. How does Spring Security work?
Spring Security places a chain of filters in front of the application. They handle authentication (who you are) and authorisation (what you may do). Adding the starter secures all endpoints by default, and you customise rules with a SecurityFilterChain bean.
Q39. What is JWT authentication?
After login, the server issues a signed JSON Web Token. The client sends it in the Authorization: Bearer header on each request, and a filter validates the signature and expiry, so the server does not need to store sessions.
Q40. How do you store passwords securely?
Never store plain text. Use a PasswordEncoder such as BCryptPasswordEncoder, which hashes passwords with a salt.
Q41. What are microservices?
Microservices split an application into small, independently deployable services, each owning its data and communicating through REST or messaging. Spring Boot is widely used to build them.
Q42. Which Spring Cloud components are used with microservices?
Spring Cloud Gateway for API routing, Eureka or Consul for service discovery, Spring Cloud Config for central configuration, OpenFeign for declarative REST clients, and Resilience4j for circuit breakers and retries.
Q43. What is a circuit breaker?
A circuit breaker stops calling a failing service after repeated errors and returns a fallback response, then tries again after a while. It prevents one failing service from bringing down the others.
Q44. How do microservices communicate?
Synchronously through REST or gRPC, using RestTemplate, WebClient or OpenFeign, or asynchronously through message brokers such as Kafka or RabbitMQ.
7. Testing and Deployment Interview Questions
Q45. How do you test a Spring Boot application?
Use JUnit 5 and Mockito for unit tests. @SpringBootTest loads the full context for integration tests, @WebMvcTest tests controllers with MockMvc, and @DataJpaTest tests repositories with an in-memory database.
Q46. What is the difference between @Mock and @MockBean?
@Mock is from Mockito and creates a mock in a plain unit test. @MockBean (replaced by @MockitoBean in newer versions) adds a mock into the Spring application context, replacing the real bean.
Q47. How do you deploy a Spring Boot application?
Build an executable JAR with Maven or Gradle and run it with java -jar, package it in a Docker image, and deploy to a server, Kubernetes or a cloud platform such as AWS, Azure or Google Cloud.
Q48. What is the difference between Spring Boot 2 and Spring Boot 3?
Spring Boot 3 requires Java 17 or later, moves from javax.* to jakarta.* packages, is based on Spring Framework 6, and adds better support for native images and observability.
How to Prepare for a Spring Boot Interview
- Know core Java first: OOP, collections and exceptions are asked alongside Spring Boot.
- Explain the layers: controller, service and repository, and why each exists.
- Understand the annotations: be ready to explain what each one does, not just name it.
- Build a REST API project: CRUD, validation, exception handling, JPA and JWT security.
- Learn microservice basics: service discovery, API gateway and circuit breakers.
Next steps: revise Java interview questions and SQL interview questions, and see all subjects on our interview questions page.
More interview preparation: see all interview questions, including Python, SQL, SQL query, Java, JavaScript, React, C++, .NET, Spring Boot, Node.js, DSA, OOPs, DBMS, operating system, networking, machine learning, data science, AI, Excel, Power BI, DevOps, manual testing, Selenium, cyber security and HR.
Frequently Asked Questions
Which Spring Boot topics are most asked for freshers?
Dependency injection, @SpringBootApplication, auto-configuration, starters, REST controllers, Spring Data JPA, exception handling and @Transactional are asked in almost every fresher interview.
Should I learn Spring before Spring Boot?
Learn core Java first, then Spring Boot directly, while understanding the core Spring ideas it uses, such as beans and dependency injection.
Is Spring Boot good for getting a job in India?
Yes. Java with Spring Boot is one of the most requested back-end skill sets in Indian IT service and product companies.
How should I prepare for a Spring Boot interview?
Build a REST API project with CRUD operations, validation, exception handling, JPA and JWT security, and be ready to explain each layer and annotation.