{jsonbody.com}

Top 40 Spring Boot Interview Questions & Answers

Top 40 Spring Boot interview questions and answers for freshers and experienced Java developers: auto-configuration, DI, REST APIs, JPA, security and testing.

Loading…

Spring Boot Basics

Q1. What is Spring Boot?

A framework on top of Spring that builds production-ready apps with little setup. It adds auto-configuration, starter dependencies, an embedded server and production features such as health checks.

Q2. What is the difference between Spring and Spring Boot?

Spring is the core framework for dependency injection, web, data and more, but needs manual configuration. Spring Boot configures Spring automatically, so you write far less setup code.

Q3. What does @SpringBootApplication do?

It combines @Configuration, @EnableAutoConfiguration and @ComponentScan. It marks the main class and starts scanning for components in its package and sub-packages.

Q4. What is auto-configuration?

Spring Boot looks at the classpath and existing beans and configures what is likely needed. For example, with spring-boot-starter-web on the classpath, it sets up Spring MVC and an embedded Tomcat.

Q5. What are Spring Boot starters?

Dependency bundles such as spring-boot-starter-web or spring-boot-starter-data-jpa that bring in compatible libraries for a feature, so you avoid version conflicts.

Q6. What is the embedded server in Spring Boot?

A web server such as Tomcat, Jetty or Undertow packaged inside the app. The app runs as a single executable JAR with java -jar, with no separate server install.

Q7. How do application.properties and application.yml work?

They hold configuration such as server.port or database URLs. Boot reads them at startup, and the YAML form is easier to read for nested settings.

Q8. What are Spring profiles?

Named sets of configuration, such as dev and prod, in files like application-prod.yml. Activate one with spring.profiles.active to switch settings per environment.

Q9. How do you read configuration values in code?

Use @Value("${app.name}") for single values, or bind a group of properties to a class with @ConfigurationProperties(prefix = "app"), which is type-safe.

Q10. How do you change the default port?

Set server.port=8081 in application.properties, or pass --server.port=8081 on the command line. Setting it to 0 picks a random free port.

Dependency Injection & Beans

Q11. What is Inversion of Control?

The framework, not your code, creates objects and wires their dependencies. The Spring container manages these objects, called beans.

Q12. What are the types of dependency injection in Spring?

Constructor, setter and field injection. Constructor injection is recommended because dependencies are explicit, can be final, and the class is easy to test.

Q13. What is the difference between @Component, @Service, @Repository and @Controller?

All register a class as a bean. @Service marks business logic, @Repository marks data access and translates database exceptions, and @Controller marks web controllers.

Q14. What is the difference between @Bean and @Component?

@Component goes on your own class so scanning finds it. @Bean goes on a method in a @Configuration class and registers whatever object it returns, which suits third-party classes.

Q15. What are bean scopes?

singleton (the default) creates one instance per container. prototype creates a new one each time. Web apps also have request and session scopes.

Q16. What does @Autowired do?

It asks Spring to inject a matching bean. With a single constructor it is optional, because Spring injects constructor parameters automatically.

Q17. How do you choose between two beans of the same type?

Mark one as @Primary to make it the default, or use @Qualifier("beanName") at the injection point to pick a specific one.

Q18. What is the bean lifecycle?

Spring creates the bean, injects dependencies, calls @PostConstruct methods, and when the container shuts down calls @PreDestroy methods.

Q19. What is a circular dependency, and how do you fix it?

Two beans that each need the other in their constructors. Spring Boot fails at startup by default, so fix the design by extracting shared logic into a third bean or using events.

Q20. What does @Conditional do?

It registers a bean only when a condition holds. Auto-configuration relies on variants such as @ConditionalOnClass and @ConditionalOnMissingBean so your own beans take priority.

REST APIs, Data & Transactions

Q21. What is the difference between @Controller and @RestController?

@RestController combines @Controller and @ResponseBody, so method return values are written straight to the response as JSON. @Controller usually returns view names.

Q22. What is the difference between @PathVariable and @RequestParam?

@PathVariable reads a value from the URL path, as in /users/{id}. @RequestParam reads a query parameter, as in /users?page=2.

Q23. How do you handle exceptions globally in Spring Boot?

Create a class with @RestControllerAdvice and methods marked @ExceptionHandler that turn exceptions into consistent error responses with the right status codes.

Q24. How do you validate request bodies?

Add Bean Validation annotations such as @NotBlank and @Email to the DTO, and @Valid on the controller parameter. Invalid input raises MethodArgumentNotValidException, which you can map to a 400 response.

Q25. What is Spring Data JPA?

A library that generates repository implementations. Extending JpaRepository<User, Long> gives CRUD, paging and sorting, and methods like findByEmail are implemented from their names.

Q26. What is the N+1 query problem in JPA?

Loading a list of entities and then running one extra query per entity to load a relationship. Fix it with JOIN FETCH, an @EntityGraph, or batch fetching.

Q27. What is the difference between lazy and eager fetching?

Lazy fetching loads a relationship only when accessed, while eager loads it with the parent. Prefer lazy, and fetch eagerly per query when needed.

Q28. What does @Transactional do?

It runs a method in a database transaction that commits if the method returns normally and rolls back on a runtime exception. It works through proxies, so calling it from the same class bypasses it.

Q29. What are transaction propagation types?

They define what happens when a transactional method calls another. REQUIRED (the default) joins the existing transaction, and REQUIRES_NEW suspends it and starts a separate one.

Q30. How do you return a custom status code?

Return a ResponseEntity, as in ResponseEntity.status(HttpStatus.CREATED).body(user), or add @ResponseStatus to the method.

Security, Testing & Production

Q31. How does Spring Security work?

A chain of servlet filters intercepts each request to authenticate the user and check permissions. You configure it with a SecurityFilterChain bean.

Q32. How do you secure a REST API with JWT?

Configure Spring Security as an OAuth2 resource server, or add a filter that validates the token from the Authorization header. Keep the API stateless with no server sessions.

Q33. What is Spring Boot Actuator?

A module that adds production endpoints such as /actuator/health and /actuator/metrics. Expose only the ones you need, and secure them.

Q34. What is the difference between @SpringBootTest and @WebMvcTest?

@SpringBootTest starts the full application context for integration tests. @WebMvcTest loads only the web layer for one controller, which is faster, with other beans mocked.

Q35. What is @MockBean?

It replaced a bean in the test context with a Mockito mock. Since Spring Boot 3.4 it is deprecated in favour of @MockitoBean.

Q36. What is Spring Boot DevTools?

A development dependency that restarts the app automatically when classes change and turns off template caching. It is disabled in packaged production builds.

Q37. How do you build microservices with Spring Boot?

Each service is its own Boot app with its own database. Spring Cloud adds service discovery, a gateway, config server and circuit breakers through Resilience4j.

Q38. What is a circuit breaker?

A pattern that stops calls to a failing service for a while and returns a fallback, so one failure does not spread. Resilience4j provides it in Spring Boot.

Q39. How do you improve Spring Boot startup time?

Use lazy initialisation, remove unused starters, or compile a GraalVM native image for near-instant startup and low memory use.

Q40. How do you run scheduled jobs in Spring Boot?

Add @EnableScheduling and mark methods with @Scheduled(fixedRate = 60000) or a cron expression. With several instances, use a lock such as ShedLock so the job runs once.