FroquizFroquiz
HomeQuizzesSenior ChallengeGet CertifiedBlogAbout
Sign InStart Quiz
Sign InStart Quiz
Froquiz

The most comprehensive quiz platform for software engineers. Test yourself with 10000+ questions and advance your career.

LinkedIn

Platform

  • Start Quizzes
  • Topics
  • Blog
  • My Profile
  • Sign In

About

  • About Us
  • Contact

Legal

  • Privacy Policy
  • Terms of Service

Β© 2026 Froquiz. All rights reserved.Built with passion for technology
Blog & Articles

Spring Boot Interview Questions and Answers (2025): From Basics to Advanced

Prepare for your Spring Boot interview with the most commonly asked questions. Covers auto-configuration, dependency injection, REST controllers, JPA, security, and more.

Yusuf SeyitoğluMarch 11, 20263 views12 min read

Spring Boot Interview Questions and Answers (2025): From Basics to Advanced

Spring Boot is the dominant Java framework for building web applications and microservices. If you are interviewing for a Java backend role, Spring Boot questions are guaranteed β€” from understanding the core concepts to writing production-ready code.

This guide covers the most frequently asked Spring Boot interview questions from basics to advanced.

Spring vs Spring Boot

Q: What is the difference between Spring and Spring Boot?

Spring Framework is a comprehensive application framework providing dependency injection, AOP, data access, transaction management, and more. Powerful but requires significant configuration.

Spring Boot is built on top of Spring and eliminates most of that configuration through:

  • Auto-configuration β€” automatically configures beans based on your classpath
  • Starter dependencies β€” curated, compatible dependency bundles
  • Embedded server β€” run as a standalone JAR with no separate Tomcat install
  • Opinionated defaults β€” sensible conventions so you write less boilerplate
java
// Traditional Spring β€” lots of XML or @Configuration classes // Spring Boot β€” this is a complete runnable application: @SpringBootApplication public class MyApp { public static void main(String[] args) { SpringApplication.run(MyApp.class, args); } }

Core Annotations

Q: What does @SpringBootApplication do?

It is a convenience annotation that combines three annotations:

  • @Configuration β€” marks the class as a source of bean definitions
  • @EnableAutoConfiguration β€” enables Spring Boot auto-configuration
  • @ComponentScan β€” scans the package and sub-packages for components

Q: What is the difference between @Component, @Service, @Repository, and @Controller?

All four are specializations of @Component β€” they all register a bean in the Spring context. The difference is semantic and functional:

AnnotationLayerExtra behavior
@ComponentGenericNone
@ServiceBusiness logicNone (semantic clarity)
@RepositoryData accessTranslates persistence exceptions to Spring exceptions
@ControllerWeb/MVCHandles HTTP requests, used with @RequestMapping
@RestControllerREST API@Controller + @ResponseBody β€” returns data, not views

Q: What is @Autowired?

@Autowired tells Spring to inject a dependency automatically. Spring finds a matching bean in its context and injects it.

java
@Service public class OrderService { private final UserRepository userRepository; // Constructor injection β€” recommended @Autowired public OrderService(UserRepository userRepository) { this.userRepository = userRepository; } }

Best practice: Prefer constructor injection over field injection (@Autowired on a field). It makes dependencies explicit, enables immutability with final, and makes testing easier.

Dependency Injection

Q: What is Inversion of Control (IoC) and Dependency Injection?

IoC is a design principle where the framework controls the flow of the application, not your code. Instead of your code creating its dependencies, the framework injects them.

Dependency Injection is the mechanism that implements IoC. Spring's IoC container creates beans, wires their dependencies, and manages their lifecycle.

java
// Without DI β€” tightly coupled public class OrderService { private UserRepository repo = new MySQLUserRepository(); // hardcoded } // With DI β€” loosely coupled @Service public class OrderService { private final UserRepository repo; // injected by Spring public OrderService(UserRepository repo) { this.repo = repo; } }

Q: What is the difference between @Bean and @Component?

  • @Component (and its specializations) are used on class definitions β€” Spring auto-detects them via component scanning
  • @Bean is used on methods inside @Configuration classes β€” you explicitly create and return the bean instance, useful for third-party classes you cannot annotate
java
// @Component β€” you own the class @Component public class MyService { } // @Bean β€” configuring a third-party class @Configuration public class AppConfig { @Bean public ObjectMapper objectMapper() { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); return mapper; } }

Q: What are bean scopes in Spring?

ScopeDescription
singleton (default)One instance per Spring context
prototypeNew instance each time requested
requestOne instance per HTTP request
sessionOne instance per HTTP session

Auto-Configuration

Q: How does Spring Boot auto-configuration work?

Spring Boot scans the classpath and applies configuration classes conditionally. When you add spring-boot-starter-data-jpa to your dependencies, Spring Boot automatically configures a DataSource, EntityManagerFactory, and transaction manager β€” if you have not already configured them yourself.

This is powered by @ConditionalOnClass, @ConditionalOnMissingBean, etc.:

java
@Configuration @ConditionalOnClass(DataSource.class) // only if DataSource is on classpath @ConditionalOnMissingBean(DataSource.class) // only if no DataSource bean defined public class DataSourceAutoConfiguration { // configure default DataSource }

Q: How do you disable specific auto-configuration?

java
@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class }) public class MyApp { }

REST Controllers

Q: How do you create a REST endpoint in Spring Boot?

java
@RestController @RequestMapping("/api/users") public class UserController { private final UserService userService; public UserController(UserService userService) { this.userService = userService; } @GetMapping public List<User> getAllUsers() { return userService.findAll(); } @GetMapping("/{id}") public ResponseEntity<User> getUser(@PathVariable Long id) { return userService.findById(id) .map(ResponseEntity::ok) .orElse(ResponseEntity.notFound().build()); } @PostMapping public ResponseEntity<User> createUser(@RequestBody @Valid CreateUserRequest request) { User created = userService.create(request); URI location = URI.create("/api/users/" + created.getId()); return ResponseEntity.created(location).body(created); } @DeleteMapping("/{id}") public ResponseEntity<Void> deleteUser(@PathVariable Long id) { userService.delete(id); return ResponseEntity.noContent().build(); } }

Q: What is the difference between @RequestParam and @PathVariable?

java
// @PathVariable β€” part of the URL path // GET /users/42 @GetMapping("/{id}") public User getUser(@PathVariable Long id) { ... } // @RequestParam β€” query parameter // GET /users?page=2&size=10 @GetMapping public Page<User> getUsers( @RequestParam(defaultValue = "0") int page, @RequestParam(defaultValue = "20") int size ) { ... }

Spring Data JPA

Q: What is Spring Data JPA and how does it work?

Spring Data JPA reduces boilerplate data access code by generating repository implementations automatically.

java
// Define an entity @Entity @Table(name = "users") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private String email; // getters, setters } // Define a repository interface β€” Spring generates the implementation public interface UserRepository extends JpaRepository<User, Long> { // Spring derives the query from the method name List<User> findByEmail(String email); List<User> findByNameContainingIgnoreCase(String name); // Custom JPQL query @Query("SELECT u FROM User u WHERE u.email = :email AND u.active = true") Optional<User> findActiveByEmail(@Param("email") String email); }

Q: What is the N+1 query problem?

When fetching a list of entities with a related collection, JPA executes one query for the list and then N additional queries β€” one for each entity's related data.

java
-- This might trigger 1 query for all orders + N queries for each order's items List<Order> orders = orderRepository.findAll(); orders.forEach(o -> o.getItems().size()); // N additional queries

Fix with JOIN FETCH:

java
@Query("SELECT o FROM Order o JOIN FETCH o.items") List<Order> findAllWithItems();

Or with @EntityGraph:

java
@EntityGraph(attributePaths = "items") List<Order> findAll();

Configuration and Properties

Q: How do you externalize configuration in Spring Boot?

Using application.properties or application.yml:

yaml
# application.yml server: port: 8080 spring: datasource: url: jdbc:postgresql://localhost:5432/mydb username: ${DB_USER} password: ${DB_PASSWORD} app: max-upload-size: 10MB allowed-origins: - https://myapp.com - https://admin.myapp.com

Access with @Value or @ConfigurationProperties:

java
// @Value β€” simple values @Value("${app.max-upload-size}") private String maxUploadSize; // @ConfigurationProperties β€” type-safe, grouped @ConfigurationProperties(prefix = "app") @Component public class AppProperties { private String maxUploadSize; private List<String> allowedOrigins; // getters, setters }

Q: What are Spring profiles?

Profiles let you define environment-specific configuration:

yaml
# application-dev.yml spring: datasource: url: jdbc:h2:mem:devdb # in-memory DB for dev # application-prod.yml spring: datasource: url: jdbc:postgresql://prod-server/mydb

Activate with:

bash
java -jar app.jar --spring.profiles.active=prod

Or in application.yml:

yaml
spring: profiles: active: dev

Exception Handling

Q: How do you handle exceptions globally in Spring Boot?

java
@RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(ResourceNotFoundException.class) public ResponseEntity<ErrorResponse> handleNotFound(ResourceNotFoundException ex) { return ResponseEntity.status(HttpStatus.NOT_FOUND) .body(new ErrorResponse("NOT_FOUND", ex.getMessage())); } @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity<ErrorResponse> handleValidation(MethodArgumentNotValidException ex) { List<String> errors = ex.getBindingResult() .getFieldErrors() .stream() .map(e -> e.getField() + ": " + e.getDefaultMessage()) .collect(Collectors.toList()); return ResponseEntity.badRequest() .body(new ErrorResponse("VALIDATION_ERROR", "Validation failed", errors)); } @ExceptionHandler(Exception.class) public ResponseEntity<ErrorResponse> handleGeneral(Exception ex) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) .body(new ErrorResponse("INTERNAL_ERROR", "An unexpected error occurred")); } }

Testing

Q: How do you write tests in Spring Boot?

java
// Unit test β€” no Spring context needed @ExtendWith(MockitoExtension.class) class UserServiceTest { @Mock private UserRepository userRepository; @InjectMocks private UserService userService; @Test void shouldReturnUserWhenFound() { User user = new User(1L, "Alice", "alice@example.com"); when(userRepository.findById(1L)).thenReturn(Optional.of(user)); Optional<User> result = userService.findById(1L); assertTrue(result.isPresent()); assertEquals("Alice", result.get().getName()); } } // Integration test β€” loads Spring context @SpringBootTest @AutoConfigureMockMvc class UserControllerTest { @Autowired private MockMvc mockMvc; @Test void shouldReturn200ForGetUsers() throws Exception { mockMvc.perform(get("/api/users")) .andExpect(status().isOk()) .andExpect(jsonPath("$").isArray()); } }

Practice Spring Boot on Froquiz

Spring Boot is a deep topic β€” the best way to be ready for interviews is repeated practice. Test your Java and Spring Boot knowledge on Froquiz across beginner, intermediate, and advanced questions.

Summary

  • Spring Boot = Spring + auto-configuration + embedded server + opinionated defaults
  • @SpringBootApplication = @Configuration + @EnableAutoConfiguration + @ComponentScan
  • Prefer constructor injection over field injection
  • Auto-configuration is conditional β€” Spring only configures what you have not already configured
  • Spring Data JPA generates repository implementations from interface methods
  • Profiles separate environment-specific config (dev, staging, prod)
  • @RestControllerAdvice centralizes exception handling across all controllers
  • Test with Mockito for unit tests, @SpringBootTest + MockMvc for integration tests

About Author

Yusuf Seyitoğlu

Author β†’

Other Posts

  • System Design Fundamentals: Scalability, Load Balancing, Caching and DatabasesMar 12
  • CSS Advanced Techniques: Custom Properties, Container Queries, Grid Masonry and Modern LayoutsMar 12
  • GraphQL Schema Design: Types, Resolvers, Mutations and Best PracticesMar 12
All Blogs