THE MODN CHRONICLES

Interview Prep

Interview Questions on Spring Boot — Core Concepts, REST APIs, and Microservices

Spring Boot powers 70% of Java backend projects in Indian IT companies. If you are interviewing for any Java backend role, Spring Boot questions are guaranteed. Here is what they ask — from annotations to microservices.

Developer working on Spring Boot code during interview preparation

Spring Boot is the default Java backend framework — every interviewer expects you to know it inside out.

The Spring Boot Interview Landscape

Spring Boot is the default Java backend framework in India. TCS, Infosys, Wipro, and every product company uses it. The interview tests whether you understand auto-configuration, dependency injection, and how Spring Boot simplifies Spring.

Unlike core Java interviews that focus on language features, Spring Boot interviews test your ability to build production-ready applications. Interviewers want to know if you can set up a REST API, connect to a database, handle exceptions properly, and explain the magic behind auto-configuration.

This guide covers the actual Spring Boot questions asked in Indian interviews — organized by topic, with code examples and the depth interviewers expect at different experience levels.

Spring Boot interviews are not about memorizing annotations. They are about understanding why auto-configuration exists and how dependency injection makes your code testable.

Core Concepts

These three questions form the foundation of every Spring Boot interview. Get these wrong and the interview is effectively over — get them right with depth and you set the tone for everything that follows.

Q1: What is Spring Boot and how is it different from Spring Framework?

Why they ask: This tests whether you understand that Spring Boot is not a replacement for Spring — it is a layer on top that provides auto-configuration, embedded servers, and opinionated defaults to eliminate boilerplate.

What the interviewer wants: Mention auto-configuration, embedded Tomcat/Jetty, starter dependencies, and how Spring Boot eliminates XML configuration. The key insight: Spring Boot makes Spring production-ready with minimal setup.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

// This single class replaces:
// - web.xml configuration
// - dispatcher servlet setup
// - component scanning configuration
// - embedded server configuration
// Spring Boot auto-configures everything based on your classpath

Q2: Explain dependency injection with an example

Why they ask: Dependency injection is the core principle of Spring. If you cannot explain it clearly with code, interviewers question whether you actually understand the framework you claim to use daily.

Key point: Constructor injection is preferred over field injection. Explain why — it makes dependencies explicit, enables immutability, and makes unit testing easier (you can pass mocks through the constructor).

@Service
public class UserService {

    private final UserRepository userRepository;

    // Constructor injection (preferred)
    @Autowired
    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public User findById(Long id) {
        return userRepository.findById(id)
            .orElseThrow(() -> new UserNotFoundException(id));
    }
}

// Why constructor injection is better than @Autowired on fields:
// 1. Dependencies are explicit — you see them in the constructor
// 2. Fields can be final — immutable after construction
// 3. Easy to test — pass mocks via constructor, no reflection needed
// 4. Fails fast — missing dependency caught at startup, not runtime

Q3: What is auto-configuration and how does it work?

Why they ask: Auto-configuration is the magic behind Spring Boot. Interviewers want to know if you understand the mechanism or just enjoy the convenience without knowing how it works.

// @EnableAutoConfiguration triggers the auto-configuration process
// Spring Boot reads META-INF/spring.factories (or spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports)
// Each auto-configuration class uses conditional annotations:

@Configuration
@ConditionalOnClass(DataSource.class)
@ConditionalOnProperty(name = "spring.datasource.url")
public class DataSourceAutoConfiguration {
    // This bean is ONLY created if:
    // 1. DataSource.class is on the classpath
    // 2. spring.datasource.url property is set
}

// Common conditional annotations:
// @ConditionalOnClass — class exists on classpath
// @ConditionalOnMissingBean — no bean of this type already defined
// @ConditionalOnProperty — specific property is set
// @ConditionalOnWebApplication — running as a web app

What separates good answers: Mentioning that you can override any auto-configured bean by defining your own. Spring Boot uses @ConditionalOnMissingBean so your custom beans always take priority over auto-configured ones.

Annotations Deep Dive

Spring Boot annotations are the most frequently tested topic in interviews. Interviewers expect you to know not just what each annotation does, but what it combines and when to use one over another.

Q1: What does @SpringBootApplication do?

Why they ask: This is the single most asked Spring Boot annotation question. It tests whether you know that @SpringBootApplication is a convenience annotation that combines three annotations into one.

// @SpringBootApplication combines three annotations:

// 1. @Configuration — marks this class as a source of bean definitions
// 2. @EnableAutoConfiguration — enables Spring Boot auto-configuration
// 3. @ComponentScan — scans the current package and sub-packages for components

@SpringBootApplication
// is equivalent to:
@Configuration
@EnableAutoConfiguration
@ComponentScan
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

// Important: @ComponentScan scans from the package where this class lives
// That is why your main class should be in the root package

Q2: Explain @RestController vs @Controller

Why they ask: This tests whether you understand the difference between returning views (HTML) and returning data (JSON/XML). In modern API development, @RestController is the default choice.

// @RestController = @Controller + @ResponseBody
// Every method automatically serializes return value to JSON

@RestController
@RequestMapping("/api/users")
public class UserController {

    @GetMapping("/{id}")
    public User getUser(@PathVariable Long id) {
        return userService.findById(id); // Returns JSON automatically
    }
}

// @Controller — returns view names (for server-side rendering)
@Controller
public class PageController {

    @GetMapping("/home")
    public String home(Model model) {
        model.addAttribute("message", "Welcome");
        return "home"; // Returns the view name "home.html"
    }
}

// Use @RestController for REST APIs (most common in interviews)
// Use @Controller for Thymeleaf/JSP server-side rendering

Q3: What are @RequestMapping, @GetMapping, @PostMapping?

Why they ask: HTTP method mapping is fundamental to building REST APIs. Interviewers want to see that you know the shortcut annotations and can handle path variables and request parameters.

@RestController
@RequestMapping("/api/products") // Base path for all methods
public class ProductController {

    // @GetMapping is shortcut for @RequestMapping(method = GET)
    @GetMapping
    public List<Product> getAll() {
        return productService.findAll();
    }

    // Path variable
    @GetMapping("/{id}")
    public Product getById(@PathVariable Long id) {
        return productService.findById(id);
    }

    // Request parameters: /api/products/search?name=phone&minPrice=500
    @GetMapping("/search")
    public List<Product> search(
        @RequestParam String name,
        @RequestParam(required = false, defaultValue = "0") Double minPrice
    ) {
        return productService.search(name, minPrice);
    }

    // @PostMapping with request body
    @PostMapping
    public Product create(@RequestBody @Valid Product product) {
        return productService.save(product);
    }
}
Code editor showing Spring Boot REST API implementation

Spring Boot REST APIs follow a layered architecture — Controller, Service, Repository. Know each layer and its responsibility.

REST API Questions

Building REST APIs is the most practical skill tested in Spring Boot interviews. Interviewers often ask you to build a complete CRUD API or explain how you handle exceptions in production applications.

Q1: Build a CRUD REST API for a User entity

Why they ask: This is the practical test. Interviewers want to see if you can write a complete three-layer architecture (Controller → Service → Repository) from memory. This question appears in almost every Spring Boot interview.

// Entity
@Entity
@Table(name = "users")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String email;
    // getters, setters, constructors
}

// Repository
public interface UserRepository extends JpaRepository<User, Long> {
    Optional<User> findByEmail(String email);
}

// Service
@Service
public class UserService {
    private final UserRepository userRepository;

    @Autowired
    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public List<User> findAll() { return userRepository.findAll(); }
    public User findById(Long id) {
        return userRepository.findById(id)
            .orElseThrow(() -> new UserNotFoundException(id));
    }
    public User save(User user) { return userRepository.save(user); }
    public void delete(Long id) { userRepository.deleteById(id); }
}

// Controller
@RestController
@RequestMapping("/api/users")
public class UserController {
    private final UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping
    public List<User> getAll() { return userService.findAll(); }

    @GetMapping("/{id}")
    public User getById(@PathVariable Long id) { return userService.findById(id); }

    @PostMapping
    public ResponseEntity<User> create(@RequestBody @Valid User user) {
        return ResponseEntity.status(HttpStatus.CREATED).body(userService.save(user));
    }

    @PutMapping("/{id}")
    public User update(@PathVariable Long id, @RequestBody User user) {
        user.setId(id);
        return userService.save(user);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> delete(@PathVariable Long id) {
        userService.delete(id);
        return ResponseEntity.noContent().build();
    }
}

Q2: How do you handle exceptions in Spring Boot REST APIs?

Why they ask: Exception handling separates junior developers from experienced ones. Interviewers want to see @ControllerAdvice with @ExceptionHandler — the centralized approach that keeps controllers clean.

// Custom exception
public class UserNotFoundException extends RuntimeException {
    public UserNotFoundException(Long id) {
        super("User not found with id: " + id);
    }
}

// Global exception handler
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(UserNotFoundException.class)
    public ResponseEntity<ErrorResponse> handleUserNotFound(UserNotFoundException ex) {
        ErrorResponse error = new ErrorResponse(
            HttpStatus.NOT_FOUND.value(),
            ex.getMessage()
        );
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(error);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<ErrorResponse> handleValidation(MethodArgumentNotValidException ex) {
        String message = ex.getBindingResult().getFieldErrors().stream()
            .map(e -> e.getField() + ": " + e.getDefaultMessage())
            .collect(Collectors.joining(", "));
        ErrorResponse error = new ErrorResponse(HttpStatus.BAD_REQUEST.value(), message);
        return ResponseEntity.badRequest().body(error);
    }
}

// Error response DTO
public record ErrorResponse(int status, String message) {}

Database & JPA

Spring Data JPA simplifies database access dramatically. Interviewers test whether you understand the repository pattern, derived query methods, and the ORM annotations that map Java objects to database tables.

Q1: What is Spring Data JPA and how does it simplify database access?

Why they ask: Spring Data JPA eliminates boilerplate DAO code. Interviewers want to know if you understand derived query methods (Spring generates SQL from method names) and when to use @Query for complex queries.

public interface UserRepository extends JpaRepository<User, Long> {

    // Derived query methods — Spring generates SQL from method name
    List<User> findByName(String name);
    List<User> findByEmailContaining(String keyword);
    List<User> findByAgeGreaterThanOrderByNameAsc(int age);

    // Custom JPQL query
    @Query("SELECT u FROM User u WHERE u.email = :email AND u.active = true")
    Optional<User> findActiveByEmail(@Param("email") String email);

    // Native SQL query
    @Query(value = "SELECT * FROM users WHERE department = ?1", nativeQuery = true)
    List<User> findByDepartment(String department);
}

// JpaRepository provides out of the box:
// save(), findById(), findAll(), deleteById(), count()
// No implementation needed — Spring generates it at runtime

Q2: Explain the difference between @Entity, @Table, @Column

Why they ask: JPA annotations for ORM mapping are fundamental. The follow-up trap question is about Lazy vs Eager loading — most candidates get this wrong.

@Entity                          // Marks this class as a JPA entity
@Table(name = "employees")       // Maps to "employees" table (optional if same name)
public class Employee {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "full_name", nullable = false, length = 100)
    private String name;           // Maps to "full_name" column

    @Column(unique = true)
    private String email;

    // Lazy vs Eager loading (the trap question)
    @OneToMany(fetch = FetchType.LAZY)   // Default for collections
    private List<Order> orders;          // Loaded only when accessed

    @ManyToOne(fetch = FetchType.EAGER)  // Default for single entities
    private Department department;       // Loaded immediately with Employee
}

// LAZY = loaded on demand (better performance, risk of LazyInitializationException)
// EAGER = loaded immediately (simpler but can cause N+1 query problem)
// Best practice: use LAZY and fetch explicitly when needed

The trap: Interviewers ask about the N+1 query problem. If you load 100 employees with EAGER departments, that is 1 query for employees + 100 queries for departments = 101 queries. The fix: use JOIN FETCH in JPQL or @EntityGraph.

Microservices Questions

Microservices questions are mandatory for candidates with 3+ years of experience. Interviewers test whether you understand service communication patterns and the Spring Cloud ecosystem.

Q1: How do you implement microservices communication in Spring Boot?

Why they ask: Microservices need to talk to each other. Interviewers want to know if you understand the options and trade-offs between synchronous and asynchronous communication.

// Option 1: RestTemplate (deprecated but still asked about)
RestTemplate restTemplate = new RestTemplate();
User user = restTemplate.getForObject("http://user-service/api/users/1", User.class);

// Option 2: WebClient (recommended — non-blocking)
@Service
public class OrderService {
    private final WebClient webClient;

    public OrderService(WebClient.Builder builder) {
        this.webClient = builder.baseUrl("http://user-service").build();
    }

    public Mono<User> getUser(Long id) {
        return webClient.get()
            .uri("/api/users/{id}", id)
            .retrieve()
            .bodyToMono(User.class);
    }
}

// Option 3: Feign Client (declarative — cleanest)
@FeignClient(name = "user-service")
public interface UserClient {
    @GetMapping("/api/users/{id}")
    User getUserById(@PathVariable Long id);
}

// Synchronous: RestTemplate, WebClient (blocking), Feign
// Asynchronous: WebClient (reactive), message queues (RabbitMQ, Kafka)

Q2: What is Spring Cloud and which components have you used?

Why they ask: This question is for 3+ years experience. Interviewers want to know if you have worked with the Spring Cloud ecosystem in production or just read about it.

// Spring Cloud components commonly asked about:

// 1. Eureka — Service Discovery
// Services register themselves, other services discover them by name
@EnableEurekaClient  // on each microservice
@EnableEurekaServer  // on the discovery server

// 2. API Gateway (Spring Cloud Gateway)
// Single entry point, routing, load balancing, rate limiting
spring.cloud.gateway.routes[0].id=user-service
spring.cloud.gateway.routes[0].uri=lb://USER-SERVICE
spring.cloud.gateway.routes[0].predicates[0]=Path=/api/users/**

// 3. Config Server — centralized configuration
// All microservices pull config from one place
@EnableConfigServer  // on the config server

// 4. Circuit Breaker (Resilience4j)
// Prevents cascading failures when a service is down
@CircuitBreaker(name = "userService", fallbackMethod = "fallbackGetUser")
public User getUser(Long id) {
    return userClient.getUserById(id);
}

public User fallbackGetUser(Long id, Throwable t) {
    return new User(id, "Default User", "N/A");
}

Key insight: Do not just list components — explain which ones you have actually used and why. Interviewers can tell the difference between textbook knowledge and production experience.

How to Prepare — By Company Type

The depth of Spring Boot knowledge tested varies by company type. Here is what each expects and how long to prepare:

Service Companies (TCS, Infosys, Wipro, Cognizant)

Preparation time: 1-2 weeks. Focus on annotations and CRUD operations. Know @SpringBootApplication (the three annotations it combines), build a basic REST API from memory, explain dependency injection with constructor injection. They test breadth, not depth. Be able to explain 15-20 annotations and build a simple CRUD API.

Product Companies (Flipkart, Razorpay, Swiggy, Zerodha)

Preparation time: 3-4 weeks. Focus on microservices and system design. Beyond CRUD, they test exception handling patterns, JPA performance (N+1 problem, lazy loading), microservices communication, and how you would design a system using Spring Boot. Know WebClient, Feign Client, and circuit breaker patterns.

GCCs (Google, Amazon, Microsoft India)

Preparation time: 4-6 weeks. Focus on internals and advanced patterns. They test auto-configuration internals (how spring.factories works), custom starters, advanced JPA (entity graphs, projections, specifications), reactive programming with WebFlux, and production concerns (monitoring with Actuator, distributed tracing, containerization).

Practice With Real Interview Simulations

Reading Spring Boot questions is not the same as answering them under pressure. Practice with timed mock interviews that test your ability to explain auto-configuration, build APIs from memory, and discuss microservices architecture.

TRY INTERVIEW PRACTICE →

Spring Boot interviews are not about memorizing annotations. They are about understanding why auto-configuration exists and how dependency injection makes your code testable.

Spring Boot is the backbone of Java backend development in India. Service companies test annotations and CRUD, product companies test microservices and system design, and GCCs test internals and advanced patterns. The good news: Spring Boot has a clear learning path. Master the three-layer architecture (Controller, Service, Repository), understand auto-configuration, and practice building APIs from memory. Every API you build in practice is one less you will struggle with in the interview.

Prepare for Your Spring Boot Interview

Practice with AI-powered mock interviews, get your resume ATS-ready, and walk into your next Spring Boot interview with confidence.

Free · AI-powered · Instant feedback