LearnFrenzy
Sign in Take a free test

Java Programming interview · Set 7 of 13

Spring Boot Interview Questions

  • 5 follow-up questions
  • 4 key points
  • Code examples
Test yourself

How Spring Boot interviews flow

Usually: core container (DI, beans, scopes) → web layer (controllers, validation, errors) → data layer (JPA, transactions, performance) → production (profiles, configuration, Actuator, security). Be ready to connect them in one request's journey.

  • ContainerDependency injection, auto-configuration and scopes.
  • WebREST controllers, validation and global errors.
  • DataJPA, transactions and the N+1 problem.

Spring Boot is the default framework for Java backend jobs, so most Java interviews spend half the time here. Expect questions on how Spring wires your objects, how a request reaches your controller, and how data and transactions behave. Answers below use Spring Boot 3 conventions.

1. What is dependency injection and why does Spring use it?

Instead of a class creating its own dependencies with new, the Spring container creates them and passes them in. This keeps classes loosely coupled, easy to test with mocks, and configurable without code changes. Prefer constructor injection: dependencies are explicit, fields can be final, and the class cannot exist half-initialised.

@Service
public class OrderService {
    private final PaymentClient payments;
    private final OrderRepository orders;

    public OrderService(PaymentClient payments, OrderRepository orders) {   // no @Autowired needed
        this.payments = payments;
        this.orders = orders;
    }
}

2. How does Spring Boot auto-configuration work?

@SpringBootApplication combines @Configuration, @ComponentScan and @EnableAutoConfiguration. Auto-configuration classes (listed in the AutoConfiguration.imports file of each starter) create beans only when their conditions match — @ConditionalOnClass, @ConditionalOnMissingBean, properties and so on. Add spring-boot-starter-data-jpa and a DataSource appears; define your own bean and Boot backs off.


3. What are bean scopes?

singleton (default): one instance per container. prototype: a new instance every time it is requested. Web scopes: request, session and application. Because singletons are shared across threads, keep them stateless.


4. @Component, @Service, @Repository and @Controller — what is the difference?

All four register a bean through component scanning. @Service and @Controller mainly document intent. @Repository also translates persistence exceptions into Spring's DataAccessException hierarchy. @RestController is @Controller plus @ResponseBody, so return values are written as JSON.


5. Build a small REST endpoint with validation and proper status codes.

Use @RestController, request DTOs with Bean Validation, and ResponseEntity for the status code.

public record CreateUser(@NotBlank String name, @Email String email) { }

@RestController
@RequestMapping("/api/users")
class UserController {
    private final UserService users;
    UserController(UserService users) { this.users = users; }

    @PostMapping
    ResponseEntity<UserDto> create(@Valid @RequestBody CreateUser req) {
        UserDto saved = users.create(req);
        return ResponseEntity.created(URI.create("/api/users/" + saved.id())).body(saved);
    }

    @GetMapping("/{id}")
    UserDto byId(@PathVariable long id) { return users.find(id); }
}

6. How do you handle exceptions globally?

Use a @RestControllerAdvice class with @ExceptionHandler methods, so every controller returns the same error format. Spring Boot 3 supports RFC 7807 ProblemDetail responses out of the box.

@RestControllerAdvice
class ApiErrors {
    @ExceptionHandler(UserNotFoundException.class)
    ProblemDetail notFound(UserNotFoundException ex) {
        return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
    }
}

7. How does @Transactional work, and when does it silently not work?

Spring wraps the bean in a proxy that begins a transaction before the method and commits or rolls back after it. By default it rolls back only on unchecked exceptions. It does not apply when you call the method from another method in the same class (self-invocation bypasses the proxy), on private methods, or when you catch the exception and swallow it.

@Transactional(rollbackFor = Exception.class)
public void placeOrder(OrderRequest req) {
    orders.save(req.toOrder());
    inventory.reserve(req.items());   // if this throws, the order insert is rolled back too
}

8. What is the N+1 query problem in JPA and how do you fix it?

Loading a list of parents runs one query, and then touching each lazy collection runs one more query per parent — 1 + N queries. Fix it with a fetch join, an @EntityGraph, or a DTO projection that selects exactly what the screen needs. Turn on SQL logging in development to catch it early.

@Query("select o from Order o join fetch o.items where o.customer.id = :id")
List<Order> findWithItems(@Param("id") long customerId);

Remember

Key points

  • Constructor injection

    Explicit, testable and allows final fields.

  • Auto-configuration is conditional

    Your own bean always wins over Boot's default.

  • Proxies power @Transactional

    Self-invocation and private methods skip it.

  • Watch your SQL

    N+1 queries are the most common JPA performance bug.

Interview drill

Follow-up questions

What the interviewer asks after your first answer. Turn on practice mode, answer each one aloud, then reveal.

  1. 1 What is the difference between @Bean and @Component? Basic

    @Component marks your own class for scanning. @Bean is a method in a @Configuration class that creates an object yourself — useful for third-party classes you cannot annotate.

  2. 2 How do you keep different settings for dev, test and production? Basic

    Use profiles: application-dev.yml, application-prod.yml, activated with spring.profiles.active. Keep secrets in environment variables or a vault, never in the repository.

  3. 3 What does Spring Boot Actuator give you? Intermediate

    Production endpoints such as /actuator/health, metrics, info and loggers, plus Micrometer integration for Prometheus or other monitoring tools. Expose only what you need and secure the rest.

  4. 4 What is the difference between Propagation.REQUIRED and REQUIRES_NEW? Advanced

    REQUIRED joins the existing transaction or starts one. REQUIRES_NEW suspends the current one and starts an independent transaction — useful for audit logs that must be saved even if the main work rolls back.

  5. 5 How do you secure a REST API in Spring Boot 3? Advanced

    Define a SecurityFilterChain bean, make the API stateless, validate JWTs with the OAuth2 resource server support, and authorise per endpoint or with @PreAuthorize.

    @Bean
    SecurityFilterChain api(HttpSecurity http) throws Exception {
        return http
            .csrf(csrf -> csrf.disable())
            .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .authorizeHttpRequests(a -> a.requestMatchers("/api/public/**").permitAll()
                                          .anyRequest().authenticated())
            .oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults()))
            .build();
    }

Preparing with friends?

Share this page with your study group or placement batch.

Search LearnFrenzy

Esc

Quick links