Jump to section

Spring Boot interview questions evaluate your ability to build production-ready Java applications using the Spring ecosystem. Interviewers test your understanding of dependency injection, auto-configuration, REST API design, data access with JPA, security configuration, and microservice architecture. These questions span beginner to advanced topics and reflect what engineering teams ask in real hiring loops.

Spring Core & Framework (Beginner) (15)

What is the Spring Framework?
easy

What they're really asking

This tests fundamental Spring Framework knowledge and whether you understand Spring's core philosophy of simplifying enterprise Java development through dependency injection and AOP.

How you'll be scored

Weak

Gives a vague definition without mentioning key concepts like dependency injection or IoC container.

Average

Correctly identifies Spring as a Java framework with dependency injection but lacks detail about its comprehensive ecosystem.

Strong

Demonstrates understanding of Spring's modular architecture, core principles, and how it solves enterprise development challenges.

How to structure your answer

  1. Define Spring Framework as comprehensive infrastructure.
  2. Explain core principles (IoC, AOP, modularity)
  3. Mention key modules and ecosystem.
  4. Connect to enterprise development benefits.

Key points to hit

  • Spring is a comprehensive framework for enterprise Java development built on IoC and AOP principles.
  • Provides modular architecture with core container, data access, web, and integration modules.
  • Simplifies enterprise development by handling cross-cutting concerns like transaction management and security.
  • Promotes loose coupling through dependency injection and interface-based programming.

Common mistakes

  • Confusing Spring Framework with Spring Boot or describing them as the same thing.
  • Only mentioning web development without recognizing Spring's broader enterprise capabilities.

Sample answer

Spring Framework is a comprehensive, modular framework for enterprise Java development that's built on two core principles: Inversion of Control and Aspect-Oriented Programming. At its heart, Spring provides an IoC container that manages object lifecycles and dependencies, which promotes loose coupling between components.

The framework includes modules for web development, data access, messaging, and security, allowing you to pick only what you need. Spring simplifies enterprise development by handling cross-cutting concerns like transaction management, security, and caching through declarative programming, so developers can focus on business logic rather than infrastructure code.

How to level up

  • Mention specific modules like Spring MVC, Spring Data, or Spring Security to show ecosystem knowledge.
  • Discuss how Spring's modularity allows you to use only needed components without bloat.
  • Connect Spring's philosophy to modern microservices architecture patterns.

Follow-up questions to expect

  • How does Spring Framework differ from Spring Boot?
  • Can you explain what the Spring IoC container does?
  • What design patterns does Spring Framework implement?
Practice this question with AI feedback →
What is Spring Boot and how is it different from the Spring Framework?
easy

What they're really asking

The interviewer wants to see that you understand the evolution from Spring to Spring Boot and can articulate why Spring Boot exists. They are gauging whether you have hands-on experience or just name recognition.

How you'll be scored

Weak

Says Spring Boot is "easier" or "simpler" without explaining what it actually does differently, or conflates Spring Boot with the full Spring ecosystem.

Average

Correctly identifies auto-configuration and embedded servers but does not connect these features to the real problems they solve.

Strong

Explains the specific pain points Spring Boot eliminates (XML config, manual dependency management, server setup), gives concrete examples, and shows understanding that Spring Boot is built on top of Spring, not a replacement.

How to structure your answer

  1. Start by defining Spring Framework: a comprehensive Java framework for building enterprise applications with dependency injection, AOP, and a modular ecosystem.
  2. Explain the friction developers faced: verbose XML or Java configuration, manual dependency version management, external application server setup.
  3. Define Spring Boot as an opinionated layer on top of Spring that provides auto-configuration, starter dependencies, and embedded servers.
  4. Give a concrete comparison: what setting up a REST API looks like in Spring vs. Spring Boot.
  5. Clarify that Spring Boot does not replace Spring. It uses Spring under the hood and lets you override any defaults.

Key points to hit

  • Spring Boot is built on top of the Spring Framework, not a separate framework.
  • Auto-configuration eliminates boilerplate by detecting what is on the classpath and configuring beans automatically.
  • Starter dependencies bundle compatible library versions so you do not manage them individually.
  • Embedded servers (Tomcat, Jetty, Undertow) let you run apps as standalone JARs without external server deployment.
  • Convention over configuration is the core philosophy, but every default can be overridden.

Common mistakes

  • Saying Spring Boot replaced or is unrelated to the Spring Framework, which shows a shallow understanding of the ecosystem.
  • Listing features without explaining the problems they solve, which sounds like you memorized a blog post rather than used it in practice.

Sample answer

Spring Framework gives you everything you need for enterprise Java, but wiring it up used to take a lot of configuration. You would write XML files or Java config classes just to get a basic web app running, and then deploy it to an external Tomcat server.

Spring Boot sits on top of Spring and removes that friction. It auto-configures your beans based on what is on the classpath, bundles compatible dependency versions through starters, and embeds a server so you can run a JAR directly.

In my last project, going from zero to a working REST API with Spring Boot took about 15 minutes. With raw Spring, the same setup would have taken a full day of configuration.

How to level up

  • Mention Spring Boot Actuator for production readiness features like health checks and metrics to show you know the ecosystem beyond basics.
  • Reference how Spring Boot profiles work for environment-specific configuration, which demonstrates real production experience.
  • Note that understanding when to override auto-configuration is what separates a junior from a senior Spring Boot developer.

Follow-up questions to expect

  • How does Spring Boot auto-configuration actually work under the hood?
  • When would you choose not to use Spring Boot and stick with plain Spring?
  • How do you manage configuration across different environments in Spring Boot?
Practice this question with AI feedback →
What are the advantages of using Spring Boot?
easy

What they're really asking

This tests whether you understand Spring Boot's value proposition of convention over configuration and can articulate why teams choose it over traditional Spring Framework setup.

How you'll be scored

Weak

Lists generic benefits like 'easy to use' without explaining Spring Boot's specific advantages or auto-configuration.

Average

Mentions auto-configuration and embedded servers but doesn't explain the development velocity impact.

Strong

Demonstrates understanding of how Spring Boot's conventions reduce boilerplate, speed development, and improve production readiness.

How to structure your answer

  1. Explain convention over configuration philosophy.
  2. Detail auto-configuration and starter dependencies.
  3. Discuss embedded servers and standalone deployment.
  4. Mention production-ready features like Actuator.

Key points to hit

  • Auto-configuration eliminates boilerplate by intelligently configuring beans based on classpath dependencies.
  • Starter dependencies provide curated, tested dependency combinations for common use cases.
  • Embedded servers enable standalone JAR deployment without external application servers.
  • Production-ready features like health checks, metrics, and externalized configuration come out of the box.

Common mistakes

  • Claiming Spring Boot is faster at runtime when the advantage is development speed, not execution speed.
  • Not understanding that Spring Boot is an opinionated layer on top of Spring Framework, not a replacement.

Sample answer

Spring Boot's main advantage is that it follows convention over configuration, which dramatically reduces the amount of boilerplate code and XML configuration you need to write. Auto-configuration automatically sets up beans based on what's in your classpath, so if you add spring-boot-starter-web, it automatically configures an embedded Tomcat server, Spring MVC, and JSON serialization.

The starter dependencies give you curated sets of compatible libraries, so you don't have to figure out which versions work together. Plus, you get production-ready features like health checks and metrics through Actuator without any additional setup, and you can deploy as a standalone JAR with an embedded server.

How to level up

  • Quantify the development speed improvement by mentioning reduced configuration time or faster onboarding.
  • Discuss how Spring Boot's opinionated defaults can be overridden when needed for customization.
  • Mention specific production benefits like easier containerization and cloud deployment.

Follow-up questions to expect

  • What happens when Spring Boot's auto-configuration doesn't match your requirements?
  • How do you exclude specific auto-configuration classes?
  • What are some drawbacks of using Spring Boot's conventions?
Practice this question with AI feedback →
What are the key components of Spring Boot?
easy

What they're really asking

This tests your understanding of Spring Boot's architecture and whether you can identify the essential components that make Spring Boot work effectively.

How you'll be scored

Weak

Lists surface-level features without understanding the underlying components or their relationships.

Average

Correctly identifies key components like auto-configuration and starters but lacks depth about how they work together.

Strong

Demonstrates understanding of how components interact and their specific roles in Spring Boot's architecture.

How to structure your answer

  1. Start with Spring Boot's foundation on Spring Framework.
  2. Explain auto-configuration mechanism and @EnableAutoConfiguration.
  3. Detail starter dependencies and their role.
  4. Cover embedded servers and production features.

Key points to hit

  • Auto-configuration classes that conditionally create beans based on classpath scanning and @Conditional annotations.
  • Starter POMs that provide curated dependency management for specific functionality.
  • Embedded servlet containers (Tomcat, Jetty, Undertow) that eliminate external server dependencies.
  • Spring Boot Actuator for production monitoring, health checks, and application introspection.

Common mistakes

  • Confusing Spring Boot components with general Spring Framework components.
  • Not understanding that auto-configuration is conditional and can be overridden or excluded.

Sample answer

The key components of Spring Boot start with auto-configuration, which uses @EnableAutoConfiguration to scan your classpath and automatically configure beans based on what dependencies are present. Starter dependencies like spring-boot-starter-web bundle related libraries with compatible versions, so you get everything you need for web development in one dependency.

Embedded servers are crucial because they let you run applications as standalone JARs without deploying to external servers. Finally, Spring Boot Actuator provides production-ready features like health endpoints, metrics collection, and application monitoring that you can expose via HTTP or JMX without writing any additional code.

How to level up

  • Mention @Conditional annotations and how they enable smart auto-configuration decisions.
  • Discuss the spring.factories file and how Spring Boot discovers auto-configuration classes.
  • Explain how Spring Boot's opinionated defaults can be customized through properties or custom configuration classes.

Follow-up questions to expect

  • How does Spring Boot's auto-configuration determine which beans to create?
  • What is the difference between @SpringBootApplication and @EnableAutoConfiguration?
  • How can you create a custom Spring Boot starter?
Practice this question with AI feedback →
What is Inversion of Control (IoC)?
easy

What they're really asking

This tests fundamental understanding of IoC as a design principle and whether you can explain how it reduces coupling and improves testability in Spring applications.

How you'll be scored

Weak

Gives a textbook definition without explaining the practical benefits or how Spring implements IoC.

Average

Correctly explains control inversion but doesn't connect it to dependency management and testing benefits.

Strong

Demonstrates understanding of how IoC improves design quality, testability, and maintainability with concrete examples.

How to structure your answer

  1. Define IoC as control inversion principle.
  2. Contrast with traditional object creation patterns.
  3. Explain Spring's IoC container implementation.
  4. Connect to benefits like loose coupling and testability.

Key points to hit

  • IoC inverts control of object creation and dependency management from application code to an external container.
  • Objects declare what they need rather than creating dependencies themselves, reducing tight coupling.
  • Spring's IoC container manages bean lifecycle, instantiation, and dependency injection automatically.
  • Enables easier testing through dependency substitution and better separation of concerns.

Common mistakes

  • Confusing IoC with Dependency Injection when IoC is the broader principle and DI is one implementation technique.
  • Not explaining the practical benefits beyond the theoretical concept.

Sample answer

Inversion of Control is a design principle where instead of objects creating their own dependencies, an external container takes control of creating and managing those dependencies. In traditional programming, if ClassA needs ClassB, ClassA would directly instantiate ClassB, creating tight coupling.

With IoC, ClassA declares it needs ClassB through a constructor parameter or setter, and Spring's IoC container handles creating ClassB and injecting it into ClassA.

This inversion makes your code more testable because you can easily substitute mock objects for dependencies, and it reduces coupling because ClassA doesn't need to know how to create ClassB, just how to use it.

How to level up

  • Provide a concrete code example showing constructor injection to illustrate the concept clearly.
  • Explain how IoC enables configuration changes without code changes through externalized bean definitions.
  • Connect IoC to SOLID principles, particularly Dependency Inversion Principle.

Follow-up questions to expect

  • What's the difference between IoC and Dependency Injection?
  • How does Spring's IoC container manage bean lifecycles?
  • What are the different ways to configure IoC container in Spring?
Practice this question with AI feedback →
What is Dependency Injection and what are its types?
easy

What they're really asking

This tests your knowledge of DI as Spring's primary mechanism for implementing IoC and whether you understand the practical differences between injection types.

How you'll be scored

Weak

Provides basic definition without explaining injection types or their appropriate use cases.

Average

Lists injection types correctly but doesn't explain when to use each type or their trade-offs.

Strong

Demonstrates understanding of injection mechanisms, their use cases, and current best practices like preferring constructor injection.

How to structure your answer

  1. Define dependency injection as IoC implementation technique.
  2. Explain the three main types with examples.
  3. Discuss when to use each type.
  4. Mention current best practices and Spring's recommendations.

Key points to hit

  • Constructor injection ensures required dependencies are provided at object creation and supports immutable objects.
  • Setter injection allows optional dependencies and circular dependencies but can create partially initialized objects.
  • Field injection using @Autowired is concise but makes testing harder and hides dependencies.
  • Spring recommends constructor injection for required dependencies as it promotes better design and testability.

Common mistakes

  • Recommending field injection as a best practice when it actually makes testing more difficult.
  • Not understanding that constructor injection helps identify design problems like too many dependencies.

Sample answer

Dependency Injection is how Spring implements IoC by automatically providing objects with their required dependencies. There are three main types: constructor injection, where dependencies are passed through the constructor and marked with @Autowired; setter injection, where dependencies are set through setter methods; and field injection, where @Autowired is placed directly on fields.

Constructor injection is generally preferred because it ensures all required dependencies are provided at creation time, makes objects immutable, and makes dependencies explicit for testing. I use setter injection only for optional dependencies, and I avoid field injection because it makes unit testing harder since you can't easily substitute mock dependencies.

How to level up

  • Mention that @Autowired on constructors is optional when there's only one constructor in Spring 4.3+.
  • Discuss how constructor injection helps identify code smells like having too many dependencies.
  • Explain @Qualifier annotation for resolving ambiguity when multiple beans of the same type exist.

Follow-up questions to expect

  • How do you handle circular dependencies in Spring?
  • What happens when Spring can't find a bean to inject?
  • How do you inject collections of beans or conditional dependencies?
Practice this question with AI feedback →
What is the Spring IoC container?
easy

What they're really asking

This tests foundational Spring knowledge and whether you understand inversion of control as a core design principle. The interviewer wants to see if you grasp how Spring manages object lifecycles and dependencies.

How you'll be scored

Weak

Vague explanation about 'managing objects' without understanding dependency injection or lifecycle management.

Average

Correctly explains IoC and mentions dependency injection but lacks depth on lifecycle management or practical benefits.

Strong

Demonstrates clear understanding of IoC principles, lifecycle management, and explains how it reduces coupling in real applications.

How to structure your answer

  1. Define IoC container and its purpose.
  2. Explain dependency injection mechanism.
  3. Describe bean lifecycle management.
  4. Contrast with traditional object creation.
  5. Mention practical benefits in Spring Boot context.

Key points to hit

  • IoC container manages object creation and dependency injection.
  • Spring's ApplicationContext is the main IoC container implementation.
  • Container handles complete bean lifecycle from instantiation to destruction.
  • Promotes loose coupling through dependency injection rather than hard-coded dependencies.

Common mistakes

  • Confusing IoC container with just dependency injection without mentioning lifecycle management.
  • Not explaining how it differs from manual object creation and wiring.

Sample answer

The Spring IoC container is the core of the Spring framework that manages object creation and dependency injection. Instead of objects creating their own dependencies, the container instantiates beans and injects their dependencies automatically. For example, if I have a UserService that needs a UserRepository, I don't create the repository myself.

The container creates both objects and injects the repository into the service based on annotations like @Autowired. This inverts the control of object creation from the application code to the framework, which reduces coupling and makes testing much easier since I can easily swap dependencies.

How to level up

  • Explain how Spring Boot's auto-configuration leverages the IoC container to reduce boilerplate.
  • Mention how the container enables AOP by creating proxies around beans.
  • Discuss how container initialization affects application startup time in microservices.

Follow-up questions to expect

  • How does Spring resolve circular dependencies?
  • What happens if the container finds multiple beans of the same type?
  • How does Spring Boot's auto-configuration work with the IoC container?
Practice this question with AI feedback →
What is a Spring Bean?
easy

What they're really asking

This tests whether you understand Spring's fundamental building blocks and how objects are managed within the IoC container. The interviewer wants to see if you know how beans differ from regular Java objects.

How you'll be scored

Weak

Says beans are just Java objects without explaining container management or Spring-specific characteristics.

Average

Correctly identifies beans as container-managed objects but doesn't explain lifecycle or configuration aspects.

Strong

Explains beans as container-managed objects with lifecycle, demonstrates understanding of configuration methods, and mentions practical implications.

How to structure your answer

  1. Define what makes an object a Spring bean.
  2. Explain container management vs regular objects.
  3. Describe how beans are configured and created.
  4. Mention bean lifecycle and scope implications.
  5. Give concrete examples in Spring Boot context.

Key points to hit

  • Beans are objects managed by the Spring IoC container.
  • Container controls bean instantiation, configuration, and lifecycle.
  • Beans can be configured through annotations, XML, or Java configuration.
  • Spring Boot auto-configuration creates many beans automatically through starter dependencies.

Common mistakes

  • Thinking all Java objects in a Spring application are beans.
  • Not understanding that beans must be registered with the container to be managed.

Sample answer

A Spring bean is a Java object that's managed by the Spring IoC container. What makes it special is that the container handles its entire lifecycle - creation, dependency injection, and destruction. I can create beans using annotations like @Component, @Service, or @Repository, or through @Bean methods in configuration classes.

For example, when I annotate a class with @Service, Spring Boot automatically detects it during component scanning and registers it as a bean. The key difference from regular objects is that I don't use 'new' to create them - I let Spring inject them where needed using @Autowired.

How to level up

  • Explain how Spring Boot's @ConditionalOn annotations affect bean creation.
  • Mention bean post-processors and how they modify beans during initialization.
  • Discuss how beans enable cross-cutting concerns through AOP proxying.

Follow-up questions to expect

  • How do you create a custom bean configuration?
  • What's the difference between @Component and @Bean?
  • How does Spring Boot decide which beans to create automatically?
Practice this question with AI feedback →
What bean scopes does Spring support?
easy

What they're really asking

This tests your understanding of bean lifecycle management and how Spring controls object instances across different contexts. The interviewer wants to see if you understand when new instances are created versus reused.

How you'll be scored

Weak

Lists some scopes without understanding when to use each or their practical implications.

Average

Names the main scopes correctly but lacks depth on use cases or web-specific scopes.

Strong

Explains all major scopes with clear use cases and demonstrates understanding of when each scope is appropriate in real applications.

How to structure your answer

  1. List the main Spring bean scopes.
  2. Explain singleton scope as the default.
  3. Describe prototype scope for new instances.
  4. Cover web-specific scopes and their contexts.
  5. Provide practical examples of when to use each scope.

Key points to hit

  • Singleton scope creates one instance per container (default behavior)
  • Prototype scope creates new instances every time the bean is requested.
  • Web scopes (request, session, application) tie bean lifecycle to HTTP contexts.
  • Scope choice affects memory usage and state management in applications.

Common mistakes

  • Assuming prototype beans are automatically garbage collected (they're not managed by container after creation)
  • Not understanding that web scopes require a web-aware ApplicationContext.

Sample answer

Spring supports six main bean scopes. Singleton is the default - one instance per container, perfect for stateless services like repositories. Prototype creates a new instance every time you request the bean, useful for objects that hold state.

Then there are web scopes: request scope creates one instance per HTTP request, session scope per user session, and application scope per ServletContext. I typically use singleton for services and repositories, prototype for objects that hold user-specific data, and request scope for objects that process HTTP request data like form handlers.

How to level up

  • Explain how to create custom scopes for specific use cases like tenant-specific beans.
  • Mention @Scope proxyMode and when you need it to inject shorter-scoped beans into longer-scoped ones.
  • Discuss performance implications of different scopes in high-traffic applications.

Follow-up questions to expect

  • When would you use prototype scope over singleton?
  • How do you inject a request-scoped bean into a singleton service?
  • What are the memory implications of different bean scopes?
Practice this question with AI feedback →
What is the difference between BeanFactory and ApplicationContext?
easy

What they're really asking

This tests your understanding of Spring's container hierarchy and whether you know when to use the more lightweight BeanFactory versus the feature-rich ApplicationContext. The interviewer wants to see if you understand the trade-offs.

How you'll be scored

Weak

Mentions both are containers without explaining the functional differences or when to use each.

Average

Correctly states ApplicationContext extends BeanFactory but doesn't explain the additional features or practical implications.

Strong

Clearly explains the feature differences, demonstrates understanding of when to use each, and mentions practical implications for Spring Boot applications.

How to structure your answer

  1. Explain the inheritance relationship.
  2. Describe BeanFactory as the basic container.
  3. List ApplicationContext's additional features.
  4. Compare use cases and performance implications.
  5. Relate to Spring Boot's default usage.

Key points to hit

  • ApplicationContext extends BeanFactory interface with additional enterprise features.
  • BeanFactory provides basic IoC functionality with lazy bean initialization.
  • ApplicationContext adds event publishing, AOP integration, and eager initialization by default.
  • Spring Boot uses ApplicationContext implementations like AnnotationConfigApplicationContext or ServletWebServerApplicationContext.

Common mistakes

  • Thinking BeanFactory is obsolete (it's still used in resource-constrained environments)
  • Not understanding that ApplicationContext initializes singleton beans at startup by default while BeanFactory waits until first request.

Sample answer

BeanFactory is the basic IoC container interface that provides fundamental dependency injection capabilities. ApplicationContext extends BeanFactory and adds enterprise features like event publishing, AOP integration, and internationalization support. The key difference is initialization - BeanFactory lazily creates beans when first requested, while ApplicationContext eagerly initializes singleton beans at startup.

In practice, I always use ApplicationContext because Spring Boot provides it by default, and the additional features like @EventListener and AOP are essential for most applications. BeanFactory is mainly used in resource-constrained environments where you need minimal memory footprint.

How to level up

  • Explain how different ApplicationContext implementations (like WebApplicationContext) provide additional web-specific features.
  • Mention how to programmatically create and configure ApplicationContext for testing or embedded usage.
  • Discuss how Spring Boot's context hierarchy works with parent-child relationships.

Follow-up questions to expect

  • How does Spring Boot choose which ApplicationContext implementation to use?
  • Can you have multiple ApplicationContexts in one application?
  • What's the performance impact of eager vs lazy bean initialization?
Practice this question with AI feedback →
What does the @SpringBootApplication annotation do internally?
easy

What they're really asking

This tests your deep understanding of Spring Boot's auto-configuration magic and whether you know what happens behind the annotation. The interviewer wants to see if you understand the components that make Spring Boot work.

How you'll be scored

Weak

Says it starts the application without explaining the three component annotations or auto-configuration mechanism.

Average

Mentions it combines three annotations but doesn't explain auto-configuration or component scanning details.

Strong

Explains all three component annotations, describes auto-configuration mechanism, and demonstrates understanding of how Spring Boot reduces configuration.

How to structure your answer

  1. Break down the three meta-annotations.
  2. Explain @EnableAutoConfiguration's mechanism.
  3. Describe component scanning behavior.
  4. Explain how auto-configuration classes are loaded.
  5. Relate to Spring Boot's convention-over-configuration philosophy.

Key points to hit

  • @SpringBootApplication combines @Configuration, @EnableAutoConfiguration, and @ComponentScan.
  • @EnableAutoConfiguration uses META-INF/spring.factories to load auto-configuration classes conditionally.
  • Component scanning starts from the main class package and scans sub-packages by default.
  • Auto-configuration creates beans based on classpath contents and existing bean definitions.

Common mistakes

  • Not understanding that auto-configuration is conditional and won't create beans if you've already defined them.
  • Thinking @SpringBootApplication scans the entire classpath rather than starting from the main class package.

Sample answer

@SpringBootApplication is a meta-annotation that combines three key annotations. @Configuration marks the main class as a source of bean definitions. @ComponentScan tells Spring to scan for components starting from the current package and all sub-packages. @EnableAutoConfiguration is the magic - it looks at your classpath and automatically configures beans based on what dependencies you have.

For example, if Spring finds H2 database on the classpath, it automatically configures a DataSource. The auto-configuration classes are loaded from META-INF/spring.factories files in starter JARs and use @Conditional annotations to only create beans when appropriate conditions are met.

How to level up

  • Explain how to exclude specific auto-configuration classes using the exclude parameter.
  • Mention how to create custom auto-configuration classes for reusable components.
  • Discuss the order of auto-configuration and how @AutoConfigureBefore/@AutoConfigureAfter control loading sequence.

Follow-up questions to expect

  • How can you see which auto-configuration classes were applied?
  • What happens if auto-configuration conflicts with your manual configuration?
  • How do you create a custom Spring Boot starter with auto-configuration?
Practice this question with AI feedback →
What is the purpose of @ComponentScan?
easy

What they're really asking

This tests whether you understand Spring Boot's component discovery mechanism and can configure package scanning appropriately. The interviewer wants to see if you know how Spring finds and registers beans automatically.

How you'll be scored

Weak

Only mentions that @ComponentScan finds components without explaining how it works or where it's used.

Average

Correctly explains that it scans packages for components but lacks detail about configuration options.

Strong

Demonstrates understanding of basePackages configuration, default behavior with @SpringBootApplication, and performance implications of scan scope.

How to structure your answer

  1. Define what @ComponentScan does in component discovery.
  2. Explain the default scanning behavior in Spring Boot.
  3. Show how to customize package scanning.
  4. Discuss performance and best practices.

Key points to hit

  • @ComponentScan tells Spring which packages to scan for @Component, @Service, @Repository, and @Controller annotations.
  • @SpringBootApplication includes @ComponentScan by default, scanning the current package and subpackages.
  • You can specify basePackages or basePackageClasses to control scan scope.
  • Narrow scanning scope improves application startup time by reducing the number of classes to examine.

Common mistakes

  • Forgetting that @SpringBootApplication already includes @ComponentScan, so adding it explicitly is often redundant.
  • Setting overly broad scan packages that hurt startup performance.

Sample answer

The @ComponentScan annotation tells Spring which packages to scan for components like @Service, @Repository, and @Controller classes. In Spring Boot, @SpringBootApplication already includes @ComponentScan, so it automatically scans the main class package and all subpackages. If I need to scan additional packages outside this hierarchy, I can specify basePackages like @ComponentScan(basePackages = "com.company.external").

It's important to keep the scan scope narrow because Spring has to examine every class in the specified packages, which can slow down application startup if you scan too broadly.

How to level up

  • Use basePackageClasses instead of basePackages for type-safe package references that survive refactoring.
  • Consider using @Import for specific configuration classes instead of broad component scanning.
  • Monitor application startup time when adding new scan packages to catch performance regressions.

Follow-up questions to expect

  • How would you exclude certain components from being scanned?
  • What happens if you have duplicate component names across different packages?
  • When might you choose explicit bean configuration over component scanning?
Practice this question with AI feedback →
How does a Spring Boot application get started?
easy

What they're really asking

This tests your understanding of Spring Boot's application lifecycle and auto-configuration magic. The interviewer wants to see if you know what happens during startup beyond just "run the main method."

How you'll be scored

Weak

Only mentions SpringApplication.run() without explaining what actually happens during startup.

Average

Lists the basic steps like classpath scanning and auto-configuration but lacks depth.

Strong

Explains the complete startup sequence including auto-configuration conditionals, bean creation order, and application context initialization.

How to structure your answer

  1. Describe the entry point with SpringApplication.run()
  2. Explain auto-configuration and classpath scanning.
  3. Detail bean creation and dependency injection.
  4. Cover application context initialization and startup events.

Key points to hit

  • SpringApplication.run() creates and refreshes the ApplicationContext.
  • Auto-configuration classes are loaded based on classpath contents and @Conditional annotations.
  • Component scanning finds and registers user-defined beans.
  • Embedded server (Tomcat/Jetty) starts automatically for web applications.

Common mistakes

  • Thinking auto-configuration always runs regardless of dependencies on the classpath.
  • Not understanding that user beans can override auto-configured beans.

Sample answer

A Spring Boot application starts when SpringApplication.run() is called from the main method. First, it creates an ApplicationContext and loads auto-configuration classes based on what's found on the classpath. For example, if spring-boot-starter-web is present, it automatically configures Tomcat and DispatcherServlet. Then it scans for user-defined components using @ComponentScan, creates beans, and injects dependencies.

Finally, it starts the embedded server and publishes application events to signal that startup is complete. The beauty is that most of this happens automatically through convention over configuration.

How to level up

  • Use ApplicationStartup to measure and optimize startup performance in production.
  • Implement ApplicationListener or use @EventListener to hook into startup events.
  • Consider using @Lazy loading for beans that aren't needed immediately to improve startup time.

Follow-up questions to expect

  • How can you customize the SpringApplication before it runs?
  • What's the difference between ApplicationContext and BeanFactory in startup?
  • How would you debug auto-configuration issues during startup?
Practice this question with AI feedback →
What is Spring Initializr?
easy

What they're really asking

This tests whether you understand Spring Boot's project scaffolding tool and can explain its value in reducing initial setup friction. The interviewer wants to see if you know how to bootstrap projects efficiently.

How you'll be scored

Weak

Only knows it creates Spring Boot projects without explaining how or why it's useful.

Average

Correctly describes it as a project generator but misses the dependency management benefits.

Strong

Explains how it generates production-ready project structure with proper dependency versions and build configuration.

How to structure your answer

  1. Define Spring Initializr as a project bootstrapping tool.
  2. Explain how it handles dependency management and compatibility.
  3. Describe the different ways to access it.
  4. Highlight the value of getting a production-ready structure.

Key points to hit

  • Spring Initializr generates Spring Boot project scaffolding with proper build files and structure.
  • It ensures compatible dependency versions through curated starter dependencies.
  • Available through start.spring.io web interface, IDE plugins, and command line.
  • Creates production-ready structure with proper package organization and configuration files.

Common mistakes

  • Thinking it only creates basic projects when it actually handles complex dependency compatibility.
  • Not understanding that it solves the Maven/Gradle version conflict problem.

Sample answer

Spring Initializr is a web-based tool at start.spring.io that generates Spring Boot project scaffolding. You select your build tool, Java version, and dependencies, and it creates a complete project with proper Maven or Gradle configuration. The key value is that it handles dependency version compatibility automatically through Spring Boot's curated starters.

Instead of figuring out which version of Jackson works with which version of Spring Web, Initializr gives you a tested combination. You get a production-ready project structure with application.properties, proper package layout, and even a basic test class.

How to level up

  • Use the REST API at start.spring.io to script project generation for team templates.
  • Customize Initializr in enterprise environments to include company-specific dependencies and configurations.
  • Save time by bookmarking URLs with your common dependency combinations.

Follow-up questions to expect

  • How would you add dependencies to an existing Spring Boot project that wasn't created with Initializr?
  • What are the advantages of Spring Boot starters over individual dependencies?
  • Can you create custom Spring Boot starters for your organization?
Practice this question with AI feedback →
What is the Spring Boot CLI?
easy

What they're really asking

This tests knowledge of Spring Boot's command-line tooling and whether you understand alternative development workflows. The interviewer wants to see if you know about rapid prototyping capabilities.

How you'll be scored

Weak

Doesn't know what Spring Boot CLI is or confuses it with other command-line tools.

Average

Knows it runs Groovy scripts but doesn't explain the auto-import magic or use cases.

Strong

Explains how CLI enables rapid prototyping with auto-imports and when it's more appropriate than full project setup.

How to structure your answer

  1. Define Spring Boot CLI as a command-line tool for Groovy scripts.
  2. Explain the auto-import and dependency resolution features.
  3. Describe typical use cases and advantages.
  4. Mention installation and basic usage.

Key points to hit

  • Spring Boot CLI runs Groovy scripts with automatic Spring Boot setup and dependency resolution.
  • Auto-imports common Spring annotations and classes without explicit import statements.
  • Perfect for rapid prototyping, testing concepts, and creating simple microservices.
  • Eliminates build file management and project structure for quick experiments.

Common mistakes

  • Thinking it's only for production applications when it's primarily a prototyping tool.
  • Not realizing that Groovy knowledge is helpful but not required for basic usage.

Sample answer

The Spring Boot CLI is a command-line tool that lets you run Groovy scripts with automatic Spring Boot configuration. You can write a simple REST controller in a .groovy file, and the CLI automatically imports Spring annotations and resolves dependencies.

For example, I can create a file with just @RestController and @RequestMapping annotations, run 'spring run app.groovy', and get a working web service without any build files or project structure. It's fantastic for quick prototypes, testing Spring concepts, or creating simple microservices when you don't want the overhead of a full Maven project.

How to level up

  • Use the CLI's 'grab' annotations to explicitly manage dependencies when auto-resolution isn't sufficient.
  • Combine CLI with Spring Cloud features for rapid microservice prototyping.
  • Package CLI applications as executable JARs using the 'jar' command for distribution.

Follow-up questions to expect

  • When would you choose CLI over a traditional Spring Boot project?
  • How does the CLI handle dependency version conflicts in complex scripts?
  • Can you debug Spring Boot CLI applications in an IDE?
Practice this question with AI feedback →

Spring Core & Framework (Intermediate) (17)

What is the difference between constructor injection and setter injection?
medium

What they're really asking

This tests your understanding of dependency injection patterns and their trade-offs in Spring. The interviewer wants to see if you can choose the right injection strategy and understand immutability principles.

How you'll be scored

Weak

Lists differences without explaining when to use each or understanding the immutability benefits.

Average

Correctly explains the mechanics but doesn't discuss testing implications or Spring's recommendations.

Strong

Demonstrates understanding of immutability, testability, and why Spring recommends constructor injection for required dependencies.

How to structure your answer

  1. Define both injection types and their syntax.
  2. Explain immutability and required dependency differences.
  3. Compare testability and initialization timing.
  4. State Spring's recommendations and best practices.

Key points to hit

  • Constructor injection creates immutable objects and ensures required dependencies are available at object creation.
  • Setter injection allows optional dependencies and runtime reconfiguration but creates mutable objects.
  • Constructor injection makes unit testing easier by forcing explicit dependency provision.
  • Spring recommends constructor injection for required dependencies and setter injection for optional ones.

Common mistakes

  • Using @Autowired on fields instead of constructors, which makes testing harder.
  • Not understanding that constructor injection prevents circular dependencies better than setter injection.

Sample answer

Constructor injection passes dependencies through the constructor, creating immutable objects where all required dependencies are guaranteed to be present. Setter injection uses setter methods, allowing optional dependencies and runtime changes but creating mutable objects.

I prefer constructor injection for required dependencies because it makes the class immutable, easier to test since I can create instances without Spring, and prevents null pointer exceptions from missing dependencies. For optional dependencies that might change at runtime, setter injection makes sense. Spring actually recommends constructor injection as the default approach since Spring 4.3.

How to level up

  • Use @RequiredArgsConstructor from Lombok to eliminate boilerplate constructor code while maintaining constructor injection benefits.
  • Be aware that constructor injection can reveal circular dependency issues that setter injection might hide.
  • Consider using Java records with Spring Boot 2.6+ for naturally immutable configuration classes.

Follow-up questions to expect

  • How do you handle circular dependencies when using constructor injection?
  • When might you choose field injection despite its disadvantages?
  • How does constructor injection affect Spring's proxy creation for AOP?
Practice this question with AI feedback →
What is the difference between @Component, @Service, @Repository, and @Controller?
medium

What they're really asking

The interviewer wants to know if you understand Spring's stereotype annotations and whether you pick the right one based on layer responsibilities, or if you just slap @Component on everything.

How you'll be scored

Weak

Says they are all the same and interchangeable without understanding their semantic or technical differences.

Average

Correctly identifies each annotation's intended layer but misses the special behavior that @Repository and @Controller provide.

Strong

Explains the semantic purpose of each, the exception translation that @Repository enables, and how @Controller ties into DispatcherServlet.

How to structure your answer

  1. State that all four are specializations of @Component and are picked up by component scanning.
  2. Explain the semantic meaning of each annotation and its target architectural layer.
  3. Highlight the technical extras that @Repository and @Controller add beyond simple bean registration.
  4. Mention best practices for choosing the right annotation.

Key points to hit

  • @Component is the generic stereotype for any Spring-managed bean that does not fit a specific layer.
  • @Service marks service-layer classes and carries no extra technical behavior but signals business logic intent.
  • @Repository marks data access classes and enables automatic persistence exception translation into Spring DataAccessException hierarchy.
  • @Controller marks web layer classes and works with DispatcherServlet to handle HTTP requests and resolve views.

Common mistakes

  • Claiming the annotations are purely cosmetic with zero functional difference, which ignores @Repository exception translation and @Controller request mapping.
  • Using @Component everywhere instead of the appropriate stereotype, which hurts code readability and disables layer-specific features.

Sample answer

All four annotations are specializations of @Component, so Spring's component scanning picks them all up and registers them as beans. The difference is both semantic and, in some cases, functional. @Component is the generic catch-all for any managed bean. @Service goes on your business logic layer.

It does not add technical behavior, but it clearly communicates intent. @Repository is for data access classes and enables Spring's persistence exception translation, which converts JDBC or JPA exceptions into Spring's DataAccessException hierarchy. @Controller marks web-layer classes and integrates with DispatcherServlet so that @RequestMapping methods are discovered for HTTP handling.

In practice, I always use the most specific annotation because it improves readability and ensures I get the framework behavior tied to each layer.

How to level up

  • Mention that @RestController combines @Controller and @ResponseBody, removing the need for @ResponseBody on every method.
  • Explain that custom stereotype annotations can be created by meta-annotating with @Component.
  • Discuss how @Repository exception translation requires a PersistenceExceptionTranslationPostProcessor bean, which Spring Boot auto-configures.

Follow-up questions to expect

  • What happens if you use @Component instead of @Repository on a DAO class?
  • How does Spring's component scanning discover these annotations?
  • Can you create your own custom stereotype annotation?
Practice this question with AI feedback →
What is the difference between @Bean and @Component?
medium

What they're really asking

The interviewer wants to see if you understand the two main approaches to bean registration in Spring and can articulate when method-level @Bean declarations are necessary versus class-level @Component scanning.

How you'll be scored

Weak

Confuses the two or says they do the same thing without explaining the declaration context difference.

Average

Correctly states @Bean is method-level and @Component is class-level but does not explain when you would pick one over the other.

Strong

Explains the declaration mechanism, ownership context, and gives concrete examples of when @Bean is the only option, such as third-party library classes.

How to structure your answer

  1. Define @Component as a class-level annotation discovered by component scanning.
  2. Define @Bean as a method-level annotation inside @Configuration classes.
  3. Explain when you must use @Bean versus when @Component works.
  4. Discuss practical scenarios for each approach.

Key points to hit

  • @Component annotates your own classes and relies on classpath scanning to register them as beans.
  • @Bean annotates methods inside @Configuration classes and gives you full programmatic control over bean instantiation.
  • @Bean is required when you need to register third-party library classes that you cannot annotate with @Component.
  • @Bean methods let you apply custom initialization logic, set properties, or conditionally create beans.

Common mistakes

  • Saying @Bean and @Component are interchangeable when @Bean is essential for third-party classes you do not own.
  • Forgetting that @Bean methods must live inside a @Configuration or @Component class to be processed.

Sample answer

@Component is a class-level annotation you put on your own classes. Spring discovers them through classpath scanning and registers them as beans automatically. @Bean is a method-level annotation you use inside @Configuration classes, where the method body creates and returns the bean instance. The key difference is control and ownership.

If I have a third-party class like a RestTemplate or an ObjectMapper, I cannot add @Component to their source code, so I write a @Bean method that instantiates and configures them exactly how I need.

In my projects, I use @Component and its specializations for my own service and repository classes, and @Bean methods for infrastructure beans and third-party integrations where I need fine-grained configuration.

How to level up

  • Mention that @Configuration uses CGLIB proxying to ensure @Bean methods called internally return the same singleton instance.
  • Discuss @Bean with @Conditional annotations for environment-specific bean creation.
  • Explain lite mode when @Bean is declared inside a @Component class versus full mode in @Configuration.

Follow-up questions to expect

  • What happens if you declare a @Bean method inside a @Component class instead of a @Configuration class?
  • How do you control the initialization order of @Bean methods?
  • Can a @Bean method reference another @Bean method in the same configuration class?
Practice this question with AI feedback →
What is the @Configuration annotation and what problem does it solve?
medium

What they're really asking

The interviewer wants to verify you understand how Java-based configuration replaced XML in Spring and why @Configuration classes behave differently from regular @Component classes.

How you'll be scored

Weak

Describes @Configuration as just another way to declare beans without understanding CGLIB proxying or its relationship to XML config.

Average

Correctly explains that @Configuration replaces XML and hosts @Bean methods but misses the proxying behavior difference.

Strong

Explains CGLIB proxying, singleton guarantee for inter-bean references, and the migration path from XML to Java-based configuration.

How to structure your answer

  1. Define @Configuration as a class that provides bean definitions to the Spring IoC container.
  2. Explain how it replaced XML-based configuration.
  3. Discuss CGLIB proxying and why it matters for singleton guarantees.
  4. Show how @Bean methods interact within a configuration class.

Key points to hit

  • @Configuration marks a class as a source of bean definitions, replacing traditional XML configuration files.
  • Spring creates a CGLIB proxy of @Configuration classes so that @Bean method calls between beans return the same singleton instance.
  • This proxying ensures that calling one @Bean method from another does not create duplicate instances.
  • @Configuration classes support @Import for composing multiple configurations and @PropertySource for loading external properties.

Common mistakes

  • Not understanding that @Configuration classes are proxied, which is what guarantees singleton behavior for inter-bean references.
  • Treating @Configuration and @Component as identical when they have different proxying semantics.

Sample answer

@Configuration marks a class as a source of Spring bean definitions, essentially replacing the old XML configuration files with type-safe Java code. What makes @Configuration special is that Spring creates a CGLIB proxy subclass of it.

This proxy intercepts @Bean method calls so that if one @Bean method calls another, the container returns the existing singleton instead of creating a new instance. For example, if I have a dataSource() @Bean method and an entityManagerFactory() method that calls dataSource(), the proxy ensures both references point to the same DataSource bean.

Without @Configuration, using just @Component in lite mode, each call would create a separate instance. In practice, I use @Configuration classes to organize related infrastructure beans together and keep them separate from business logic components.

How to level up

  • Mention proxyBeanMethods attribute introduced in Spring 5.2 that lets you disable CGLIB proxying for performance when inter-bean references are not needed.
  • Discuss how @Configuration classes can use @Profile to provide environment-specific bean sets.
  • Explain the @Import annotation for composing modular configuration classes.

Follow-up questions to expect

  • What is the difference between full mode and lite mode for @Bean declarations?
  • How does @Configuration interact with @ComponentScan?
  • When would you set proxyBeanMethods to false?
Practice this question with AI feedback →
What is the @Autowired annotation and how does it work?
medium

What they're really asking

The interviewer is checking whether you understand Spring's primary dependency injection mechanism and can explain the resolution process, including what happens when multiple candidates exist.

How you'll be scored

Weak

Gives a shallow description like "it injects dependencies" without explaining the resolution algorithm or injection points.

Average

Explains constructor, setter, and field injection but does not discuss ambiguity resolution or the optional attribute.

Strong

Demonstrates understanding of the resolution process, injection points, required vs optional injection, and the shift toward constructor injection as the recommended approach.

How to structure your answer

  1. Define @Autowired as Spring's annotation for automatic dependency injection.
  2. Explain the three injection points: constructor, setter, and field.
  3. Describe the resolution algorithm: type matching, then qualifier, then name.
  4. Discuss current best practices and when @Autowired is optional.

Key points to hit

  • @Autowired tells Spring to resolve and inject a matching bean by type from the application context.
  • It can be applied to constructors, setters, or fields, with constructor injection being the recommended approach.
  • When multiple beans of the same type exist, Spring falls back to @Qualifier or bean name matching to resolve ambiguity.
  • Since Spring 4.3, @Autowired is optional on single-constructor classes because Spring auto-detects the constructor for injection.

Common mistakes

  • Not knowing that @Autowired is implicit on single constructors since Spring 4.3, which makes your code look outdated.
  • Using field injection with @Autowired in production code when constructor injection provides better testability and immutability.

Sample answer

@Autowired tells Spring to automatically inject a matching bean from the application context into a dependency. It works on constructors, setter methods, and fields. When Spring encounters @Autowired, it first looks for a bean matching the required type. If multiple candidates exist, it narrows by @Qualifier annotation, then by bean name matching the parameter name.

One thing that trips people up is that since Spring 4.3, you do not even need @Autowired on a class with a single constructor because Spring automatically uses it for injection.

In my projects, I always prefer constructor injection because it makes dependencies explicit, supports immutability with final fields, and makes unit testing straightforward since you can just pass mocks through the constructor.

How to level up

  • Mention the required attribute: @Autowired(required = false) makes the dependency optional and sets it to null if no bean is found.
  • Discuss how @Autowired works with generics for type-safe collection injection like List<PaymentProcessor>
  • Explain the @Primary annotation as an alternative to @Qualifier for setting a default bean when multiple candidates exist.

Follow-up questions to expect

  • What happens if Spring finds two beans of the same type and no @Qualifier is specified?
  • How does @Autowired interact with @Lazy for deferred initialization?
  • Why is constructor injection preferred over field injection in modern Spring applications?
Practice this question with AI feedback →
What is the @Qualifier annotation used for?
medium

What they're really asking

The interviewer wants to see if you can handle dependency ambiguity in Spring when multiple beans of the same type exist and understand the resolution strategies available.

How you'll be scored

Weak

Knows @Qualifier exists but cannot explain when or why you need it.

Average

Correctly explains that @Qualifier disambiguates between multiple beans of the same type but gives no concrete example.

Strong

Demonstrates clear understanding of @Qualifier with @Autowired, compares it to @Primary, and gives a real scenario where ambiguity occurs.

How to structure your answer

  1. Explain the problem: multiple beans of the same type cause ambiguity.
  2. Define @Qualifier as the annotation that resolves this ambiguity by name.
  3. Show how it works alongside @Autowired.
  4. Compare with @Primary as an alternative strategy.

Key points to hit

  • @Qualifier specifies which bean to inject when multiple candidates of the same type exist in the application context.
  • It works alongside @Autowired on constructors, setters, or fields to narrow the selection by bean name.
  • @Primary is an alternative that marks one bean as the default choice, but @Qualifier overrides @Primary when both are present.
  • Custom qualifier annotations can be created for more semantic and type-safe disambiguation.

Common mistakes

  • Confusing @Qualifier with @Primary, or not understanding that @Qualifier takes precedence over @Primary.
  • Not knowing you can create custom qualifier annotations for better type safety instead of relying on string-based names.

Sample answer

When you have multiple beans of the same type, Spring cannot decide which one to inject and throws a NoUniqueBeanDefinitionException. @Qualifier solves this by letting you specify the exact bean name you want.

For example, if I have two DataSource beans, one for the primary database and one for reporting, I would declare them with @Bean names like "primaryDataSource" and "reportingDataSource". Then at the injection point, I use @Autowired together with @Qualifier("reportingDataSource") to pick the right one.

An alternative is @Primary, which sets a default, but @Qualifier gives you explicit control and takes precedence when both are present. In complex applications, I sometimes create custom qualifier annotations like @ReportingDatabase to avoid magic strings and get compile-time safety.

How to level up

  • Show how to create a custom qualifier annotation with @Qualifier as a meta-annotation for type-safe disambiguation.
  • Mention that @Qualifier can be used on method parameters in @Bean methods for fine-grained injection control.
  • Discuss how Spring resolves beans: first by type, then by @Qualifier, then by parameter name as a fallback.

Follow-up questions to expect

  • What happens if both @Qualifier and @Primary point to different beans?
  • How do you create a custom qualifier annotation?
  • What is the bean resolution order when @Qualifier is not specified?
Practice this question with AI feedback →
What is bean auto-wiring and what are its modes?
medium

What they're really asking

This tests your understanding of Spring's dependency injection mechanisms and how Spring Boot simplifies bean wiring through auto-configuration. The interviewer wants to see if you understand when automatic wiring helps versus when explicit configuration is needed.

How you'll be scored

Weak

Lists autowiring modes without explaining when to use each or how Spring Boot changes the game.

Average

Correctly explains the four autowiring modes with basic examples but misses Spring Boot's @Autowired annotation focus.

Strong

Demonstrates understanding of both XML-era autowiring modes and modern annotation-driven approaches, including when each is appropriate.

How to structure your answer

  1. Define auto-wiring as Spring's automatic dependency resolution.
  2. List the four XML-based autowiring modes.
  3. Explain how @Autowired annotation supersedes XML modes.
  4. Provide concrete examples of constructor vs field injection.
  5. Discuss when to choose explicit wiring over auto-wiring.

Key points to hit

  • Spring Boot heavily favors @Autowired annotation over XML autowiring modes.
  • Constructor injection is preferred over field injection for mandatory dependencies.
  • Auto-wiring reduces boilerplate but can make dependencies less explicit.
  • Understanding when Spring's convention-over-configuration helps versus hurts maintainability.

Common mistakes

  • Focusing only on legacy XML autowiring modes without mentioning @Autowired.
  • Not explaining the trade-off between convenience and explicit dependency declaration.

Sample answer

Auto-wiring is Spring's mechanism for automatically resolving and injecting dependencies between beans. The traditional XML modes are byName, byType, constructor, and autodetect, but in Spring Boot we primarily use @Autowired annotation. For example, I prefer constructor injection like @Autowired MyService(UserRepository repo) because it makes dependencies explicit and enables immutable fields.

Field injection with @Autowired is convenient but can make testing harder since you can't easily mock dependencies. The key is understanding that auto-wiring trades some explicitness for development speed, which aligns with Spring Boot's philosophy.

How to level up

  • Discuss @Qualifier annotation for resolving ambiguous bean matches.
  • Mention @Primary annotation for setting default beans when multiple candidates exist.
  • Explain how Spring Boot's auto-configuration creates beans that participate in autowiring.

Follow-up questions to expect

  • How would you handle a circular dependency in Spring Boot?
  • When would you use @Qualifier versus @Primary for bean selection?
  • How does Spring Boot's auto-configuration affect bean autowiring?
Practice this question with AI feedback →
What are the limitations of auto-wiring?
medium

What they're really asking

This tests whether you understand the trade-offs of Spring's convention-over-configuration approach and can identify when auto-wiring creates problems in production systems. The interviewer wants to see mature thinking about dependency management.

How you'll be scored

Weak

Lists limitations without understanding their impact on real applications or how to mitigate them.

Average

Identifies key limitations like circular dependencies and debugging complexity with basic explanations.

Strong

Demonstrates experience with auto-wiring pitfalls and knows specific strategies to avoid or resolve them in production code.

How to structure your answer

  1. Acknowledge auto-wiring's convenience while introducing its constraints.
  2. Explain debugging and transparency challenges.
  3. Discuss circular dependency problems.
  4. Cover performance and ambiguity issues.
  5. Provide mitigation strategies for each limitation.

Key points to hit

  • Auto-wiring makes dependency relationships less explicit, complicating code understanding.
  • Circular dependencies become harder to detect until runtime.
  • Multiple beans of the same type create ambiguity that requires @Qualifier or @Primary.
  • Debugging becomes more complex because wiring happens behind the scenes.

Common mistakes

  • Claiming auto-wiring has no significant drawbacks or performance impact.
  • Not providing concrete examples of when explicit wiring is better.

Sample answer

The main limitation is reduced transparency since dependencies aren't explicitly declared, making code harder to understand for new team members. Circular dependencies become a real problem because Spring can't resolve them at startup, leading to runtime failures. When you have multiple implementations of an interface, auto-wiring fails with NoUniqueBeanDefinitionException unless you use @Qualifier or @Primary.

I've also seen debugging issues where it's not clear which bean instance got injected. To mitigate these, I use constructor injection to make dependencies explicit and leverage Spring Boot's fail-fast startup to catch wiring issues early.

How to level up

  • Discuss how Spring Boot's auto-configuration reports help understand bean creation order.
  • Mention using @Lazy annotation to break circular dependencies strategically.
  • Explain how actuator endpoints can help debug bean wiring in production.

Follow-up questions to expect

  • How would you debug a NoUniqueBeanDefinitionException in a large Spring Boot application?
  • What strategies do you use to prevent circular dependencies in microservices?
  • How do you balance auto-wiring convenience with code maintainability?
Practice this question with AI feedback →
What is the Bean lifecycle in Spring?
medium

What they're really asking

This tests your deep understanding of Spring's internal mechanics and whether you can troubleshoot complex initialization problems. The interviewer wants to see if you understand what happens behind Spring Boot's auto-configuration magic.

How you'll be scored

Weak

Vaguely mentions initialization and destruction without understanding the sequence or hooks available.

Average

Correctly lists the main lifecycle phases but lacks detail about when to use lifecycle callbacks.

Strong

Demonstrates practical experience with lifecycle hooks and can explain how Spring Boot's auto-configuration affects bean lifecycle.

How to structure your answer

  1. Outline the complete bean lifecycle from instantiation to destruction.
  2. Explain key lifecycle interfaces and annotations.
  3. Describe how Spring Boot auto-configuration fits into lifecycle.
  4. Provide examples of when to hook into specific lifecycle events.
  5. Discuss implications for application startup performance.

Key points to hit

  • Bean lifecycle includes instantiation, property setting, initialization callbacks, and destruction.
  • @PostConstruct and @PreDestroy are preferred over interface-based callbacks.
  • InitializingBean and DisposableBean interfaces provide programmatic lifecycle control.
  • Spring Boot's ApplicationRunner and CommandLineRunner execute after full application context startup.

Common mistakes

  • Confusing application context lifecycle with individual bean lifecycle.
  • Not understanding that @PostConstruct runs after dependency injection but before the bean is fully ready.

Sample answer

Spring's bean lifecycle starts with instantiation, then setter injection, followed by BeanNameAware and BeanFactoryAware if implemented. After that, @PostConstruct methods run, which is where I typically put initialization logic like warming caches or validating configuration. The bean is then fully ready for use. During shutdown, @PreDestroy runs for cleanup like closing connections.

In Spring Boot, I often use ApplicationRunner for logic that needs to run after the entire application context is ready, not just after individual beans. This lifecycle understanding is crucial for managing resources properly and avoiding issues like using partially initialized dependencies.

How to level up

  • Explain how @DependsOn can control bean initialization order.
  • Discuss how Spring Boot's health checks integrate with bean lifecycle.
  • Mention BeanPostProcessor for cross-cutting lifecycle concerns.

Follow-up questions to expect

  • How would you ensure a database connection pool is initialized before JPA repositories?
  • What's the difference between ApplicationRunner and CommandLineRunner?
  • How does Spring Boot's graceful shutdown affect bean destruction?
Practice this question with AI feedback →
Explain inner beans in Spring.
medium

What they're really asking

This tests your knowledge of Spring's configuration patterns and whether you understand when to use composition over standard bean definitions. The interviewer wants to see if you grasp advanced bean scoping and encapsulation strategies.

How you'll be scored

Weak

Confuses inner beans with nested classes or doesn't understand their scoping implications.

Average

Correctly explains inner beans as anonymous, nested bean definitions with basic syntax examples.

Strong

Demonstrates understanding of when inner beans improve encapsulation and their limitations compared to regular beans.

How to structure your answer

  1. Define inner beans as nested, anonymous bean definitions.
  2. Show XML and annotation-based syntax examples.
  3. Explain scoping and lifecycle characteristics.
  4. Discuss when inner beans improve design versus when they complicate it.
  5. Connect to Spring Boot's preference for annotation-based configuration.

Key points to hit

  • Inner beans are anonymous and cannot be referenced by other beans.
  • They share the lifecycle of their outer bean and cannot be injected elsewhere.
  • Useful for tightly coupled dependencies that shouldn't exist independently.
  • Spring Boot favors @Bean methods and @Configuration classes over XML inner beans.

Common mistakes

  • Thinking inner beans are the same as nested Java classes.
  • Not understanding that inner beans cannot be autowired into other components.

Sample answer

Inner beans are anonymous bean definitions nested inside another bean definition, typically used for dependencies that are tightly coupled to a single parent bean. In XML, you'd define them inline without an id attribute. In Spring Boot, I achieve similar encapsulation using @Bean methods within @Configuration classes where one method calls another private method.

For example, if I have a service that needs a specialized validator that no other component should use, I might create it as an inner bean. The key advantage is encapsulation since the inner bean can't be accidentally injected elsewhere, but the trade-off is reduced reusability.

How to level up

  • Show how @Bean methods can create inner bean relationships through method calls.
  • Discuss how inner beans affect Spring Boot's auto-configuration and component scanning.
  • Mention using @Scope on inner beans for specific lifecycle requirements.

Follow-up questions to expect

  • How would you achieve inner bean functionality using Spring Boot's annotation approach?
  • When would you choose an inner bean over a private @Bean method?
  • How do inner beans affect Spring's dependency injection debugging?
Practice this question with AI feedback →
What is Bean Wiring?
medium

What they're really asking

This tests your fundamental understanding of dependency injection concepts and how Spring Boot simplifies the wiring process. The interviewer wants to see if you understand the shift from XML configuration to annotation-driven development.

How you'll be scored

Weak

Provides a vague definition without distinguishing between manual wiring and Spring's automated approach.

Average

Explains bean wiring correctly but focuses on XML configuration without mentioning Spring Boot improvements.

Strong

Demonstrates understanding of how Spring Boot's auto-configuration and annotations revolutionized bean wiring compared to traditional Spring.

How to structure your answer

  1. Define bean wiring as the process of connecting beans with their dependencies.
  2. Contrast manual XML wiring with annotation-based approaches.
  3. Explain Spring Boot's role in simplifying wiring through auto-configuration.
  4. Provide examples of different wiring approaches.
  5. Discuss the evolution from XML to annotations to auto-configuration.

Key points to hit

  • Bean wiring connects dependencies between objects in Spring's IoC container.
  • Spring Boot dramatically reduces wiring configuration through starter dependencies and auto-configuration.
  • @ComponentScan and stereotype annotations enable automatic bean discovery.
  • Modern Spring Boot applications require minimal explicit wiring compared to XML-era Spring.

Common mistakes

  • Focusing exclusively on XML-based wiring without acknowledging Spring Boot's annotation approach.
  • Not understanding how auto-configuration affects traditional bean wiring patterns.

Sample answer

Bean wiring is the process of connecting beans with their dependencies in Spring's IoC container. Traditional Spring required extensive XML configuration to wire beans together, but Spring Boot revolutionized this with auto-configuration and annotations. Now I typically use @Autowired for dependency injection, @ComponentScan to discover beans automatically, and Spring Boot starters handle most framework-level wiring.

For example, adding spring-boot-starter-data-jpa automatically wires up entity managers, repositories, and transaction managers. The evolution from explicit XML wiring to convention-based auto-configuration represents Spring Boot's core philosophy of reducing boilerplate while maintaining flexibility when explicit configuration is needed.

How to level up

  • Explain how Spring Boot's ConditionalOnClass and ConditionalOnMissingBean enable smart auto-wiring.
  • Discuss using @Profile for environment-specific wiring strategies.
  • Show how custom auto-configuration classes can extend Spring Boot's wiring capabilities.

Follow-up questions to expect

  • How does Spring Boot decide which beans to auto-wire during startup?
  • What's the difference between component scanning and auto-configuration?
  • How would you override Spring Boot's default wiring for a specific component?
Practice this question with AI feedback →
What are Spring Profiles and how do you use them?
medium

What they're really asking

This tests your understanding of environment-based configuration management in Spring Boot. The interviewer wants to see if you can deploy the same codebase across different environments without code changes.

How you'll be scored

Weak

Only mentions profiles exist or gives vague examples without showing how to actually configure them.

Average

Correctly explains profiles and shows basic usage with @Profile or spring.profiles.active.

Strong

Demonstrates understanding of profile hierarchy, external activation, and production deployment strategies.

How to structure your answer

  1. Define what profiles are and their purpose.
  2. Show how to create profile-specific configurations.
  3. Explain activation methods.
  4. Discuss real-world usage patterns.

Key points to hit

  • Spring Profiles allow environment-specific bean configuration and property files.
  • Use @Profile annotation on beans or create application-{profile}.properties files.
  • Activate via spring.profiles.active property or command line arguments.
  • Profiles can be combined and have hierarchy for complex deployment scenarios.

Common mistakes

  • Assuming profiles are only for properties files and not understanding they control bean creation.
  • Not knowing how to externally activate profiles in production environments.

Sample answer

Spring Profiles let me configure different behaviors for different environments without changing code. I create profile-specific property files like application-dev.properties and application-prod.properties, and use @Profile annotations on configuration classes. For example, @Profile('dev') on a mock service bean. I activate profiles using spring.profiles.active in application.properties or as JVM arguments like -Dspring.profiles.active=prod.

This way the same JAR runs differently in dev versus production.

How to level up

  • Use profile groups to activate multiple related profiles at once.
  • Leverage profile-specific @ConfigurationProperties classes for complex environment configurations.

Follow-up questions to expect

  • How would you handle secrets differently across profiles?
  • Can you have multiple active profiles and how do they interact?
  • How do you test profile-specific configurations?
Practice this question with AI feedback →
Are singleton beans thread-safe in Spring?
medium

What they're really asking

This tests your understanding of Spring's default bean scope and concurrent access patterns. The interviewer wants to see if you understand thread safety implications in production systems.

How you'll be scored

Weak

Simply says yes or no without understanding the nuance of shared state versus stateless beans.

Average

Correctly states that singleton beans are shared but thread safety depends on implementation.

Strong

Explains the difference between stateless and stateful beans and provides concrete examples of thread-safe design.

How to structure your answer

  1. Clarify that Spring's singleton scope means one instance per container.
  2. Explain thread safety depends on bean implementation not Spring framework.
  3. Distinguish between stateless and stateful beans.
  4. Provide examples of thread-safe and unsafe patterns.

Key points to hit

  • Spring singleton beans are shared across all threads in the application.
  • Thread safety depends on whether the bean maintains mutable state.
  • Stateless beans with only dependencies injected are typically thread-safe.
  • Use @Scope('prototype') or ThreadLocal for beans that must maintain state.

Common mistakes

  • Assuming Spring automatically makes beans thread-safe.
  • Not understanding the difference between singleton pattern and Spring singleton scope.

Sample answer

Spring singleton beans are not automatically thread-safe because they're shared across all threads. Thread safety depends on the bean's implementation. A service bean with only @Autowired dependencies and no instance variables is thread-safe because it's stateless. But a bean that maintains counters or caches in instance variables isn't thread-safe without proper synchronization.

I design most service beans to be stateless, and use prototype scope or ThreadLocal when I need to maintain state per request.

How to level up

  • Use @Scope('request') for web applications when you need per-request state.
  • Consider using concurrent collections or atomic operations for shared mutable state in singleton beans.

Follow-up questions to expect

  • How would you make a stateful singleton bean thread-safe?
  • When would you use prototype scope in a real application?
  • What's the performance impact of prototype versus singleton scope?
Practice this question with AI feedback →
In which scenario would you use singleton vs prototype scope?
medium

What they're really asking

This tests your understanding of bean lifecycle management and when different scopes solve real architectural problems. The interviewer wants to see practical decision-making skills.

How you'll be scored

Weak

Only recites the definitions without explaining when to use each scope.

Average

Correctly explains both scopes and gives basic examples of when to use each.

Strong

Provides concrete scenarios and explains the trade-offs including performance and memory implications.

How to structure your answer

  1. Define both singleton and prototype scopes.
  2. Explain performance and memory characteristics.
  3. Provide concrete use cases for each.
  4. Discuss the decision criteria.

Key points to hit

  • Singleton creates one instance per Spring container, prototype creates new instance per injection.
  • Use singleton for stateless services, repositories, and configuration beans.
  • Use prototype for stateful beans, heavy objects that need customization, or objects with request-specific data.
  • Consider memory usage and initialization cost when choosing scope.

Common mistakes

  • Using prototype scope unnecessarily which impacts performance.
  • Not understanding that prototype beans aren't managed by Spring container after creation.

Sample answer

I use singleton scope for most beans like services and repositories because they're stateless and shared efficiently. Singleton is Spring's default and performs better since objects are created once.

I use prototype scope when I need fresh instances with different state, like a report generator that maintains processing status, or when integrating with libraries that expect new instances. For example, I used prototype scope for a PDF builder that accumulated data during generation since each request needed its own builder instance.

How to level up

  • Use @Lookup method injection to get prototype beans from singleton beans.
  • Consider request or session scope for web applications instead of prototype when appropriate.

Follow-up questions to expect

  • How do you inject prototype beans into singleton beans correctly?
  • What happens to prototype beans regarding dependency injection and lifecycle callbacks?
  • When would you use request or session scope instead?
Practice this question with AI feedback →
What is the difference between application.properties and application.yml?
medium

What they're really asking

This tests your knowledge of Spring Boot configuration formats and when to choose each. The interviewer wants to see if you understand the practical differences beyond syntax.

How you'll be scored

Weak

Only mentions they're different formats without explaining advantages or when to use each.

Average

Correctly explains both are property formats and mentions YAML supports hierarchical structure.

Strong

Compares readability, features, tooling support and provides guidance on when to choose each format.

How to structure your answer

  1. Explain both are Spring Boot configuration formats.
  2. Compare syntax and readability differences.
  3. Discuss unique features of each format.
  4. Provide selection criteria based on use case.

Key points to hit

  • Both files configure Spring Boot applications with the same underlying property system.
  • YAML supports hierarchical structure, lists, and multi-document files.
  • Properties format is simpler, widely supported, and easier for simple configurations.
  • YAML is more readable for complex nested configurations but requires proper indentation.

Common mistakes

  • Not knowing that YAML requires proper indentation and can break with formatting errors.
  • Assuming you need to choose one format when Spring Boot can use both simultaneously.

Sample answer

Both application.properties and application.yml configure Spring Boot applications, but with different syntax. Properties uses key=value format like server.port=8080, while YAML uses hierarchical structure with indentation. I prefer YAML for complex configurations because it's more readable and supports lists naturally.

For simple configurations or teams unfamiliar with YAML, properties format is safer since indentation errors in YAML can break the application. Spring Boot can actually use both files together, with properties taking precedence.

How to level up

  • Use YAML's multi-document feature to define multiple profiles in one file.
  • Leverage Spring Boot's relaxed binding to use kebab-case in YAML for readability.

Follow-up questions to expect

  • What's the precedence order when both files exist?
  • How do you handle sensitive properties in either format?
  • Can you mix profiles across both file formats?
Practice this question with AI feedback →
What is the difference between application.properties and bootstrap.properties?
medium

What they're really asking

This tests your knowledge of Spring Cloud configuration hierarchy and bootstrap context. The interviewer wants to see if you understand distributed configuration management.

How you'll be scored

Weak

Doesn't understand the difference or confuses them with profile-specific files.

Average

Correctly explains bootstrap.properties loads earlier and is used for Spring Cloud configuration.

Strong

Explains the bootstrap context, configuration precedence, and when each file is appropriate for microservices.

How to structure your answer

  1. Explain the loading order and contexts.
  2. Describe the purpose of bootstrap context.
  3. Compare use cases for each file.
  4. Discuss Spring Cloud integration.

Key points to hit

  • bootstrap.properties loads in bootstrap context before application context starts.
  • Bootstrap context configures external configuration sources like Spring Cloud Config.
  • application.properties loads in main application context for regular application configuration.
  • Bootstrap properties have higher precedence and cannot be overridden by local configuration.

Common mistakes

  • Thinking bootstrap.properties is just another profile-specific file.
  • Not understanding that bootstrap context exists primarily for Spring Cloud applications.

Sample answer

bootstrap.properties loads before application.properties in a separate bootstrap context. I use bootstrap.properties to configure external configuration sources like Spring Cloud Config Server URLs, service discovery settings, or vault connections.

This ensures the application can fetch its main configuration before the application context starts. application.properties contains the actual application configuration like database settings and business logic properties. In microservices, bootstrap.properties might have spring.cloud.config.uri while application.properties has local fallback values.

How to level up

  • Use bootstrap.properties for configuration that shouldn't change between deployments.
  • Consider that bootstrap properties cannot be refreshed via Spring Cloud Config refresh.

Follow-up questions to expect

  • How does Spring Cloud Config override local application.properties?
  • What happens if bootstrap context fails to load external configuration?
  • Can you disable bootstrap context if you're not using Spring Cloud?
Practice this question with AI feedback →
What is @ConfigurationProperties in Spring Boot?
medium

What they're really asking

The interviewer wants to see if you understand type-safe externalized configuration in Spring Boot and can explain why @ConfigurationProperties is preferred over scattered @Value annotations for managing application settings.

How you'll be scored

Weak

Vaguely describes it as a way to read properties without explaining type safety, binding, or validation capabilities.

Average

Correctly explains property binding to a POJO but misses validation support, relaxed binding, or the prefix mechanism.

Strong

Demonstrates understanding of type-safe binding, @EnableConfigurationProperties, validation with @Validated, relaxed binding rules, and nested property support.

How to structure your answer

  1. Define @ConfigurationProperties as a way to bind external properties to a strongly typed Java object.
  2. Explain the prefix mechanism and how properties map to fields.
  3. Compare with @Value for individual property injection.
  4. Discuss validation, nested objects, and immutable configuration.

Key points to hit

  • @ConfigurationProperties binds a group of related properties from application.yml or application.properties to a POJO using a prefix.
  • It provides type safety, IDE autocompletion with spring-boot-configuration-processor, and compile-time validation.
  • Supports relaxed binding so properties like server.servlet-context-path, SERVER_SERVLET_CONTEXT_PATH, and serverServletContextPath all map correctly.
  • Can be combined with @Validated and JSR-303 annotations like @NotNull and @Min for startup validation of configuration values.

Common mistakes

  • Using dozens of @Value annotations scattered across classes instead of grouping related config into a @ConfigurationProperties class.
  • Forgetting to enable configuration properties scanning with @EnableConfigurationProperties or @ConfigurationPropertiesScan.

Sample answer

@ConfigurationProperties lets you bind a group of related external properties to a strongly typed Java bean using a prefix. For example, I create a class annotated with @ConfigurationProperties(prefix = "app.mail") and define fields like host, port, and username. Spring Boot automatically binds app.mail.host, app.mail.port, and app.mail.username from my application.yml to those fields.

This is much better than using @Value on individual fields because you get type safety, IDE autocompletion when you add the spring-boot-configuration-processor, and you can validate the entire configuration at startup using @Validated with JSR-303 annotations like @NotNull.

I also like that it supports relaxed binding, so environment variables like APP_MAIL_HOST map correctly without any extra work.

How to level up

  • Mention constructor binding with @ConstructorBinding for creating immutable configuration objects that cannot be mutated after startup.
  • Discuss using @ConfigurationPropertiesScan as an alternative to @EnableConfigurationProperties for cleaner setup.
  • Explain how to use @ConfigurationProperties with @Profile for environment-specific configuration groups.

Follow-up questions to expect

  • How do you make @ConfigurationProperties objects immutable?
  • What is the difference between @ConfigurationProperties and @Value?
  • How does relaxed binding work in Spring Boot?
Practice this question with AI feedback →

Ready to put this into practice?

Try these questions in a mock interview →

Still applying for jobs? Let Auto Apply do it

Spring Core & Framework (Advanced) (8)

What causes circular dependency errors in Spring and how do you fix them?
hard

What they're really asking

The interviewer is testing whether you have encountered real-world dependency issues and understand the underlying bean creation lifecycle well enough to diagnose and fix circular references.

How you'll be scored

Weak

Knows circular dependencies are bad but cannot explain why they happen or how to resolve them.

Average

Identifies that two beans depending on each other cause the problem but only suggests @Lazy as the fix without addressing design issues.

Strong

Explains the bean creation lifecycle that causes the error, lists multiple resolution strategies, and emphasizes that circular dependencies usually signal a design problem worth refactoring.

How to structure your answer

  1. Explain what a circular dependency is and why Spring cannot resolve it with constructor injection.
  2. Describe the bean creation lifecycle step that fails.
  3. List resolution strategies from best to acceptable.
  4. Emphasize that the root cause is usually a design smell worth refactoring.

Key points to hit

  • Circular dependencies occur when BeanA requires BeanB in its constructor and BeanB requires BeanA, creating an unresolvable loop.
  • Spring Boot 2.6+ disallows circular dependencies by default and throws BeanCurrentlyInCreationException.
  • Resolution strategies include refactoring to break the cycle, using @Lazy on one constructor parameter, extracting shared logic into a third bean, or using setter injection.
  • The best fix is almost always a design refactor because circular dependencies indicate tightly coupled components that violate single responsibility.

Common mistakes

  • Immediately reaching for @Lazy or spring.main.allow-circular-references=true without considering that the dependency cycle signals a design problem.
  • Not knowing that Spring Boot 2.6+ changed the default to disallow circular references, which catches many developers upgrading from older versions.

Sample answer

Circular dependencies happen when BeanA needs BeanB in its constructor and BeanB needs BeanA, so neither can be created first. Spring Boot 2.6 and later throw a BeanCurrentlyInCreationException by default instead of silently resolving it.

The quickest fix is adding @Lazy to one of the constructor parameters, which tells Spring to inject a proxy that initializes the real bean on first use. But in my experience, the right fix is to refactor. Usually the cycle means two classes share responsibilities that should be extracted into a third bean.

For example, if UserService and OrderService depend on each other, I would extract the shared logic into a UserOrderMediator that both depend on. You can also break cycles by moving one dependency to setter injection, but that sacrifices the immutability guarantees of constructor injection.

How to level up

  • Mention that Spring used to resolve setter-based circular dependencies through early bean references, which hid design problems until runtime.
  • Discuss using ApplicationEventPublisher to decouple beans through events instead of direct references.
  • Explain how Spring's three-level cache mechanism worked for circular dependency resolution before the 2.6 default change.

Follow-up questions to expect

  • How does @Lazy actually resolve the circular dependency at runtime?
  • What is the difference between a circular dependency error at startup versus at runtime?
  • How would you detect circular dependencies before they cause runtime errors?
Practice this question with AI feedback →
Why does field injection cause testing and immutability issues?
hard

What they're really asking

The interviewer wants to see if you understand the practical downsides of field injection beyond just "constructor injection is recommended" and can explain the concrete impact on test writing and object design.

How you'll be scored

Weak

Says field injection is bad because documentation says so but cannot articulate the specific problems.

Average

Correctly identifies that you need reflection to set fields in tests but misses the immutability and hidden dependency arguments.

Strong

Explains reflection requirement for tests, hidden dependencies, lack of final field support, and the tight coupling to the Spring container that field injection creates.

How to structure your answer

  1. Explain what field injection looks like and how it works.
  2. Detail the testing problem: you cannot set private fields without reflection or Spring context.
  3. Explain the immutability problem: fields cannot be final.
  4. Discuss hidden dependencies and the violation of the explicit dependency principle.

Key points to hit

  • Field injection uses @Autowired on private fields, making them impossible to set from test code without reflection or a full Spring context.
  • Fields cannot be declared final because they are set after construction, preventing truly immutable objects.
  • Dependencies are hidden from the class API since they do not appear in the constructor signature, making it easy to add too many without noticing.
  • Classes become tightly coupled to the Spring container because there is no way to instantiate them correctly outside of it.

Common mistakes

  • Claiming field injection is always wrong when it can be acceptable in test classes themselves or simple prototypes.
  • Not providing a concrete code example of how constructor injection makes testing easier.

Sample answer

Field injection puts @Autowired on private fields, and that causes two concrete problems. First, in unit tests, you cannot set those private fields through normal Java. You either need the Mockito @InjectMocks annotation which uses reflection, or you spin up a full Spring context with @SpringBootTest, which is slow.

With constructor injection, you just pass mocks directly through the constructor. Second, field-injected fields cannot be declared final because they are assigned after the constructor runs. This means your object is mutable and could theoretically have its dependencies swapped at runtime, which is a reliability risk. There is also a subtler design issue.

When dependencies are hidden in fields, you do not feel the pain of adding the tenth dependency to a class. With constructor injection, a constructor with ten parameters is an obvious signal that the class needs refactoring.

How to level up

  • Mention that Lombok's @RequiredArgsConstructor generates constructor injection code for all final fields, giving you both immutability and concise syntax.
  • Discuss how field injection prevents the use of the class in non-Spring contexts, such as utility scripts or integration with other frameworks.
  • Explain that Spring's own documentation officially recommends constructor injection as of Spring 4.x.

Follow-up questions to expect

  • Are there any scenarios where field injection is acceptable?
  • How does Lombok help bridge the gap between field injection convenience and constructor injection benefits?
  • What is the performance difference between field injection and constructor injection?
Practice this question with AI feedback →
What are common reasons for slow Spring Boot application startup?
hard

What they're really asking

The interviewer is testing your production troubleshooting experience. They want to see if you can diagnose and optimize slow startup times, which is critical for microservices, CI/CD pipelines, and scaling scenarios.

How you'll be scored

Weak

Guesses vaguely about having too many beans without concrete diagnosis or optimization techniques.

Average

Identifies component scanning scope and auto-configuration overhead but lacks measurement or profiling strategies.

Strong

Demonstrates a systematic approach to profiling startup, identifies specific causes, and recommends actionable optimizations with real tooling.

How to structure your answer

  1. List the common culprits for slow startup.
  2. Explain diagnostic tools and techniques for measuring startup time.
  3. Provide specific optimization strategies.
  4. Mention Spring Boot features designed to address startup performance.

Key points to hit

  • Overly broad component scanning that scans the entire classpath instead of targeted packages.
  • Unnecessary auto-configuration classes loading beans you do not use, such as configuring JPA when you only need JDBC.
  • Heavy bean initialization at startup, including database connection pools, cache warming, and Hibernate schema validation.
  • Spring Boot Actuator startup endpoint and ApplicationStartup with BufferingApplicationStartup provide detailed startup timing data.

Common mistakes

  • Jumping to Spring Native or GraalVM as the first solution instead of addressing simple configuration issues first.
  • Not knowing how to profile and measure startup time, which means you are guessing instead of diagnosing.

Sample answer

The most common cause I have seen is overly broad component scanning. If your @SpringBootApplication sits in a root package, it scans everything including test utilities and third-party libraries. Narrowing @ComponentScan to specific packages can cut seconds off startup. Next is unnecessary auto-configuration.

I use the --debug flag or the conditions evaluation report to see which auto-configurations loaded, then exclude the ones I do not need with @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}). Hibernate schema validation is another big one. Setting spring.jpa.hibernate.ddl-auto to validate or none and using Flyway for migrations avoids the DDL introspection overhead.

For measurement, I use Spring Boot's ApplicationStartup with BufferingApplicationStartup to get a detailed timeline of every bean creation step, and the Actuator /startup endpoint to expose this data. In critical microservices, I have also used lazy initialization with spring.main.lazy-initialization=true to defer bean creation until first use.

How to level up

  • Mention Spring AOT processing and GraalVM native images for sub-second startup in cloud-native deployments.
  • Discuss the startup actuator endpoint and how to analyze the FlightRecorder-style startup events.
  • Explain how lazy initialization trades startup speed for slightly slower first-request latency, and when that trade-off is appropriate.

Follow-up questions to expect

  • What are the trade-offs of enabling lazy bean initialization globally?
  • How does Spring Native and GraalVM compilation affect startup time?
  • How would you profile startup time in a containerized environment?
Practice this question with AI feedback →
How can you achieve thread-safety in beans?
hard

What they're really asking

The interviewer wants to see if you understand that singleton beans are shared across threads by default and can design thread-safe components without introducing concurrency bugs.

How you'll be scored

Weak

Does not recognize that singleton beans are shared across request threads and assumes Spring handles thread safety automatically.

Average

Understands the singleton concurrency issue but only suggests synchronized blocks as a fix.

Strong

Demonstrates a range of strategies including stateless design, thread-local scope, concurrent data structures, and scoping alternatives, and knows which to apply in which context.

How to structure your answer

  1. Explain why thread safety matters for Spring beans (singleton scope is the default)
  2. List strategies from simplest to most advanced.
  3. Discuss Spring-specific scoping options.
  4. Provide guidance on choosing the right approach.

Key points to hit

  • Singleton beans are created once and shared across all threads, so any mutable instance state creates race conditions.
  • The best approach is designing stateless beans where all state lives in method parameters, local variables, or external stores.
  • When state is necessary, use thread-safe alternatives like ConcurrentHashMap, AtomicReference, or @Scope("request") for per-request state.
  • Prototype or request scope can provide per-invocation or per-request bean instances when statelessness is not possible.

Common mistakes

  • Assuming Spring beans are automatically thread-safe because the container manages them.
  • Overusing synchronized blocks everywhere instead of designing for statelessness or using appropriate scopes.

Sample answer

Since Spring beans are singleton-scoped by default, every concurrent request shares the same instance. The golden rule is to keep beans stateless. All my service and repository beans have no mutable instance fields. State flows through method parameters and return values.

When I do need shared mutable state, I use java.util.concurrent types like ConcurrentHashMap or AtomicLong instead of synchronized blocks. For request-scoped state, I use @Scope("request") or @RequestScope so each HTTP request gets its own bean instance. In one project, we had a rate limiter service that needed per-user state.

Instead of making it thread-safe with locks, I used ConcurrentHashMap with computeIfAbsent to atomically create per-user counters. Spring also offers ThreadLocal-based solutions like RequestContextHolder for accessing request data in non-controller beans.

How to level up

  • Discuss the difference between SimpleThreadScope (available in Spring) and custom thread-local scopes for batch processing scenarios.
  • Mention that @Transactional beans use ThreadLocal-bound connections, which is itself a thread-safety strategy for database access.
  • Explain how reactive programming with WebFlux changes the thread-safety model since a single request can span multiple threads.

Follow-up questions to expect

  • What happens if you store request-specific data in a singleton bean's instance variable?
  • How does @Scope("prototype") affect thread safety?
  • How do you handle thread safety in reactive Spring WebFlux applications?
Practice this question with AI feedback →
What is a Proxy in Spring and when is it used?
hard

What they're really asking

This tests deep understanding of Spring's AOP mechanism and proxy patterns. The interviewer wants to see if you understand how Spring implements cross-cutting concerns and the performance implications of different proxy strategies.

How you'll be scored

Weak

Only mentions proxies exist without explaining JDK vs CGLIB or when they're created.

Average

Explains basic proxy concept and mentions AOP but lacks detail on implementation differences.

Strong

Demonstrates understanding of both proxy types, performance trade-offs, and how to troubleshoot proxy-related issues.

How to structure your answer

  1. Define what Spring proxies are and their core purpose.
  2. Explain JDK dynamic proxies vs CGLIB proxies.
  3. Describe when Spring creates proxies automatically.
  4. Mention performance considerations and debugging tips.
  5. Provide concrete example of proxy behavior.

Key points to hit

  • Spring creates proxies for AOP, transactions, and security using either JDK dynamic proxies (interfaces) or CGLIB (classes)
  • JDK proxies require interfaces while CGLIB can proxy concrete classes but has higher startup cost.
  • @Transactional, @Cacheable, and @Async all trigger proxy creation with method interception.
  • Self-invocation within the same class bypasses proxies, causing annotations to be ignored.

Common mistakes

  • Not understanding that self-invocation bypasses proxy behavior, breaking @Transactional methods.
  • Assuming all Spring beans are proxied when proxies are only created when needed for AOP.

Sample answer

Spring uses proxies to implement cross-cutting concerns like transactions and security without modifying your actual classes. There are two types: JDK dynamic proxies for interface-based beans and CGLIB proxies for concrete classes. When you use @Transactional, Spring wraps your bean in a proxy that intercepts method calls to handle transaction boundaries.

The key gotcha is self-invocation - if a method calls another @Transactional method in the same class, the proxy is bypassed and the transaction annotation is ignored. I've debugged this issue by extracting the called method to a separate service or using AspectJ weaving instead of proxies.

How to level up

  • Use @EnableAspectJAutoProxy(proxyTargetClass = true) to force CGLIB proxies for better debugging.
  • Consider AspectJ compile-time weaving for performance-critical applications to avoid proxy overhead.
  • Debug proxy issues by checking if your bean implements interfaces and understanding the proxy creation conditions.

Follow-up questions to expect

  • How would you troubleshoot a @Transactional method that isn't working?
  • What's the performance difference between JDK and CGLIB proxies?
  • How does Spring decide whether to create a JDK or CGLIB proxy?
Practice this question with AI feedback →
How do you get the list of all beans in your Spring Boot application?
hard

What they're really asking

This tests practical debugging skills and understanding of Spring's application context internals. The interviewer wants to see if you can troubleshoot bean-related issues and understand the container's introspection capabilities.

How you'll be scored

Weak

Doesn't know how to access the ApplicationContext or mentions only basic toString methods.

Average

Knows about ApplicationContext.getBeanDefinitionNames() but lacks practical debugging context.

Strong

Provides multiple approaches including Actuator endpoints and explains when each method is useful for debugging.

How to structure your answer

  1. Explain accessing ApplicationContext in different scenarios.
  2. Show programmatic approach using getBeanDefinitionNames()
  3. Mention Actuator endpoints for runtime inspection.
  4. Discuss filtering and searching techniques.
  5. Provide practical debugging use case.

Key points to hit

  • Use ApplicationContext.getBeanDefinitionNames() programmatically or inject ApplicationContext where needed.
  • Spring Boot Actuator provides /beans endpoint for runtime inspection of all registered beans.
  • CommandLineRunner or ApplicationRunner are good places to inspect beans during startup.
  • Filter results by type using ApplicationContext.getBeansOfType() for specific bean categories.

Common mistakes

  • Forgetting that Actuator endpoints need to be enabled and secured in production environments.
  • Not understanding the difference between bean definitions and actual bean instances.

Sample answer

I typically use ApplicationContext.getBeanDefinitionNames() to get all bean names programmatically. For runtime debugging, I enable the Actuator /beans endpoint which gives you a JSON view of all beans, their types, and dependencies. In development, I sometimes create a CommandLineRunner that logs all beans of a specific type using getBeansOfType().

For example, when debugging why my custom validator wasn't working, I used getBeansOfType(Validator.class) to see all validator beans and discovered a naming conflict. The Actuator approach is especially useful because it shows the full dependency graph.

How to level up

  • Use Spring Boot's /beans Actuator endpoint with jq or similar tools to filter and search large bean lists efficiently.
  • Create custom Actuator endpoints to expose filtered bean information specific to your application's needs.
  • Combine getBeanDefinitionNames() with BeanFactory.getBeanDefinition() to inspect bean scopes and dependencies programmatically.

Follow-up questions to expect

  • How would you find all beans that implement a specific interface?
  • What's the difference between getBeanDefinitionNames() and getBeansOfType()?
  • How can you inspect bean dependencies and their initialization order?
Practice this question with AI feedback →
What is the difference between @Autowired and @Inject?
hard

What they're really asking

This tests knowledge of dependency injection standards and Spring's compliance with JSR-330. The interviewer wants to see if you understand vendor lock-in concerns and can make informed decisions about annotation choices.

How you'll be scored

Weak

Claims they're identical or only mentions that @Inject is from JSR-330.

Average

Explains JSR-330 compliance and basic differences but lacks practical implications.

Strong

Demonstrates understanding of feature differences, when to choose each, and migration considerations.

How to structure your answer

  1. Explain the origin of each annotation.
  2. Compare functional differences and capabilities.
  3. Discuss when to use each annotation.
  4. Address vendor neutrality considerations.
  5. Mention configuration and customization differences.

Key points to hit

  • @Autowired is Spring-specific with features like required=false and qualifier support, while @Inject is JSR-330 standard.
  • @Inject has no required attribute - injection always fails if no bean is found, unlike @Autowired(required=false)
  • @Autowired works with Spring's @Qualifier, while @Inject uses @Named for disambiguation.
  • @Inject requires additional dependency (javax.inject) but provides vendor neutrality across DI frameworks.

Common mistakes

  • Thinking they're completely interchangeable when @Inject lacks the required=false option.
  • Not considering the javax.inject dependency requirement when choosing @Inject.

Sample answer

@Autowired is Spring's proprietary annotation with more features, while @Inject is the JSR-330 standard annotation. The key difference is @Autowired supports required=false for optional dependencies, but @Inject always requires a matching bean or fails. @Autowired pairs with @Qualifier for disambiguation, while @Inject uses @Named.

I typically stick with @Autowired in Spring-specific projects because of the additional flexibility, but use @Inject when building libraries that might be used with other DI containers like Guice or CDI for better portability.

How to level up

  • Use @Inject in shared libraries or when following strict JSR-330 compliance requirements for vendor neutrality.
  • Consider that @Autowired's ecosystem integration is deeper with Spring Boot's configuration properties and testing annotations.
  • Remember that @Inject requires the javax.inject dependency to be explicitly included in your project.

Follow-up questions to expect

  • What other JSR-330 annotations does Spring support besides @Inject?
  • How would you handle optional dependencies when using @Inject?
  • When would you choose vendor neutrality over Spring-specific features?
Practice this question with AI feedback →
Explain how Spring Boot handles externalized configuration and its order of precedence.
hard

What they're really asking

This tests understanding of Spring Boot's configuration hierarchy and ability to manage complex deployment scenarios. The interviewer wants to see if you can design applications that work across different environments without code changes.

How you'll be scored

Weak

Only mentions application.properties files without understanding the precedence order or external sources.

Average

Lists several configuration sources but doesn't explain the precedence order or practical implications.

Strong

Demonstrates clear understanding of the 17-level precedence hierarchy and can explain how to leverage it for different deployment scenarios.

How to structure your answer

  1. Explain Spring Boot's externalized configuration philosophy.
  2. Describe the precedence order from highest to lowest priority.
  3. Give examples of common configuration sources.
  4. Explain practical use cases for different precedence levels.
  5. Discuss security considerations for sensitive properties.

Key points to hit

  • Spring Boot follows a 17-level precedence hierarchy where command-line arguments override environment variables, which override application.properties files.
  • Profile-specific properties (application-prod.properties) take precedence over default application.properties.
  • External application.properties files override internal ones, allowing deployment-time configuration changes.
  • Environment variables and system properties enable container-based deployments without rebuilding applications.

Common mistakes

  • Not understanding that profiles create their own precedence layers, leading to unexpected property overrides.
  • Putting sensitive information in application.properties files instead of using environment variables or external configuration servers.

Sample answer

Spring Boot uses a strict precedence order for configuration sources, with command-line arguments at the top, followed by environment variables, then external configuration files, and finally bundled application.properties files.

This means I can ship an application with default settings in application.properties, override them per environment using application-prod.properties, and still allow operations teams to override specific values using environment variables in containers. For example, database URLs might be in application-prod.properties, but passwords come from environment variables for security.

The key insight is that higher precedence sources only need to specify the properties they're changing, not everything.

How to level up

  • Use @ConfigurationProperties with validation annotations to catch configuration errors early rather than failing at runtime.
  • Leverage Spring Cloud Config Server for centralized configuration management across multiple services.
  • Use the /configprops Actuator endpoint to debug configuration precedence issues in non-production environments.

Follow-up questions to expect

  • How would you handle sensitive configuration data like database passwords?
  • What happens when you have conflicting values in different profile-specific property files?
  • How can you validate that required configuration properties are present at startup?
Practice this question with AI feedback →

Spring Boot Auto-Configuration (Beginner) (5)

What is Spring Boot auto-configuration?
easy

What they're really asking

This tests fundamental understanding of Spring Boot's core value proposition and convention-over-configuration philosophy. The interviewer wants to see if you grasp how auto-configuration reduces boilerplate and when it might not be appropriate.

How you'll be scored

Weak

Says it automatically configures things without explaining the mechanism or conditions.

Average

Explains that it configures beans based on classpath but lacks detail on how it works or can be customized.

Strong

Demonstrates understanding of conditional annotations, how to customize auto-configuration, and when to disable it.

How to structure your answer

  1. Define auto-configuration and its purpose in Spring Boot.
  2. Explain how it works using conditional annotations.
  3. Describe how classpath scanning triggers configuration.
  4. Mention customization and override capabilities.
  5. Give concrete example of auto-configuration in action.

Key points to hit

  • Auto-configuration automatically configures Spring beans based on classpath dependencies and existing bean definitions.
  • Uses conditional annotations like @ConditionalOnClass and @ConditionalOnMissingBean to make intelligent configuration decisions.
  • Triggered by @EnableAutoConfiguration and follows convention-over-configuration principle.
  • Can be customized through application properties or overridden by defining your own beans.

Common mistakes

  • Thinking auto-configuration can't be overridden when you can easily provide your own bean definitions.
  • Not understanding that auto-configuration only kicks in when certain conditions are met.

Sample answer

Spring Boot auto-configuration automatically sets up beans and configuration based on what's on your classpath and what beans you've already defined. For example, if Spring Boot sees the H2 database jar on the classpath and no other DataSource bean defined, it automatically configures an in-memory database.

It uses conditional annotations like @ConditionalOnClass to check for dependencies and @ConditionalOnMissingBean to avoid conflicts with your custom configurations. The beauty is that it provides sensible defaults that work out of the box, but you can override any auto-configured bean by simply defining your own version.

How to level up

  • Use the /conditions Actuator endpoint to see which auto-configuration classes were applied and why others were skipped.
  • Create your own auto-configuration classes for reusable library components using @AutoConfiguration and spring.factories.
  • Use @ConditionalOnProperty to make your custom auto-configuration respect application properties.

Follow-up questions to expect

  • How would you exclude specific auto-configuration classes if they're causing conflicts?
  • What happens if you have multiple DataSource beans defined?
  • How can you see which auto-configurations were applied to your application?
Practice this question with AI feedback →
What are Spring Boot starter dependencies?
easy

What they're really asking

The interviewer wants to see if you understand how Spring Boot simplifies dependency management and whether you have worked with starters in real projects.

How you'll be scored

Weak

Describes starters as just regular Maven dependencies without understanding the curated nature or auto-configuration trigger.

Average

Correctly explains that starters bundle related dependencies but does not mention transitive dependency management or naming conventions.

Strong

Explains the curated dependency sets, naming convention, auto-configuration trigger, and the problem starters solve around version compatibility.

How to structure your answer

  1. Define starters as curated dependency descriptors.
  2. Explain the problem they solve: version compatibility and dependency management.
  3. Give examples of common starters.
  4. Mention the naming convention and how to find them.

Key points to hit

  • Starters are curated sets of dependency descriptors that pull in all libraries needed for a specific functionality.
  • They solve the version compatibility problem by ensuring all transitive dependencies work together.
  • Official starters follow the naming convention spring-boot-starter-* (web, data-jpa, security, test)
  • Adding a starter not only brings in dependencies but also triggers related auto-configuration classes.

Common mistakes

  • Thinking starters contain application code when they are purely dependency descriptors that pull in libraries.
  • Not understanding that starters trigger auto-configuration, which is what makes Spring Boot "just work" after adding a dependency.

Sample answer

Spring Boot starters are curated sets of dependency descriptors that bundle everything you need for a specific capability.

Instead of manually adding five or six individual libraries for web development and figuring out which versions are compatible, you add spring-boot-starter-web and it pulls in Spring MVC, embedded Tomcat, Jackson for JSON, and validation libraries, all at tested and compatible versions. The naming convention is spring-boot-starter followed by the feature name.

What makes starters powerful beyond just dependency management is that adding them triggers auto-configuration. When Spring Boot sees spring-boot-starter-data-jpa on the classpath, it automatically configures a DataSource, EntityManagerFactory, and transaction manager.

How to level up

  • Mention that you can create custom starters for shared company libraries following the convention your-company-spring-boot-starter.
  • Explain that starters transitively depend on spring-boot-starter which brings in core Spring Boot infrastructure including auto-configure and logging.
  • Discuss how to analyze what a starter brings in using mvn dependency:tree or gradle dependencies.

Follow-up questions to expect

  • How do you find out what dependencies a specific starter brings in?
  • How do you exclude a transitive dependency from a starter?
  • What is the difference between spring-boot-starter and spring-boot-starter-web?
Practice this question with AI feedback →
What is the default port of Tomcat in Spring Boot?
easy

What they're really asking

The interviewer is checking basic Spring Boot knowledge and whether you have actually run a Spring Boot application. This is a quick screening question.

How you'll be scored

Weak

Does not know the default port or guesses incorrectly.

Average

Correctly states port 8080 but offers no additional context.

Strong

States port 8080 and can explain how to change it, why 8080 is chosen, and how it relates to embedded server configuration.

How to structure your answer

  1. State the default port clearly.
  2. Explain why this default was chosen.
  3. Mention how to verify and change it.

Key points to hit

  • The default port is 8080 for the embedded Tomcat server.
  • Port 8080 is the standard convention for non-privileged HTTP services, avoiding the need for root access that port 80 requires.
  • You can change it via server.port property in application.properties or application.yml.
  • Setting server.port=0 lets the OS assign a random available port, which is useful for testing.

Common mistakes

  • Confusing port 8080 with port 80 or 443.
  • Not knowing that server.port=0 assigns a random port, which is a frequently used testing technique.

Sample answer

The default embedded Tomcat port in Spring Boot is 8080. This is the convention for non-privileged HTTP services since port 80 would require root permissions on Linux.

You can verify this by starting any Spring Boot web application and checking the startup log, which says "Tomcat started on port(s): 8080." To change it, I set server.port in application.properties or pass it as a command-line argument with --server.port=9090.

In integration tests, I often use server.port=0 to let the OS assign a random available port, which prevents port conflicts when multiple test suites run in parallel.

How to level up

  • Mention that you can also set the port using the SERVER_PORT environment variable, which is useful in containerized deployments.
  • Discuss how to configure HTTPS on a different port alongside HTTP using server.ssl properties.
  • Explain that management.server.port can run Actuator endpoints on a separate port for security isolation.

Follow-up questions to expect

  • How would you configure HTTPS in Spring Boot?
  • What is the management.server.port property used for?
  • How do you run multiple Spring Boot applications on the same machine?
Practice this question with AI feedback →
How do you change the port of the embedded Tomcat server?
easy

What they're really asking

The interviewer wants to see if you know the basics of externalized configuration in Spring Boot and can configure the embedded server.

How you'll be scored

Weak

Does not know where to set the port or suggests editing Tomcat configuration files directly.

Average

Knows to set server.port in application.properties but does not mention alternative approaches.

Strong

Demonstrates multiple ways to set the port and explains the property resolution order that determines which value wins.

How to structure your answer

  1. Explain the primary method using application.properties or application.yml.
  2. Mention command-line arguments and environment variables as alternatives.
  3. Discuss the property resolution precedence.
  4. Mention the random port option for testing.

Key points to hit

  • Set server.port=9090 in application.properties or server.port: 9090 in application.yml.
  • Pass it as a command-line argument: java -jar app.jar --server.port=9090.
  • Use an environment variable: SERVER_PORT=9090.
  • Command-line arguments override properties files, and environment variables have their own place in the resolution hierarchy.

Common mistakes

  • Trying to edit an external Tomcat server.xml file, which shows a misunderstanding of embedded server configuration.
  • Not understanding the property source precedence and being surprised when a command-line argument overrides the properties file value.

Sample answer

The simplest way is to set server.port=9090 in your application.properties file or the equivalent in application.yml. You can also pass it as a command-line argument with --server.port=9090 when running the JAR, which overrides the properties file value.

In containerized environments, I prefer using the SERVER_PORT environment variable so the port is configured outside the application code. For integration tests, I use @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) which sets server.port=0 and lets the OS pick an available port automatically.

This prevents port conflicts during parallel test runs, and you can inject the actual port using @LocalServerPort.

How to level up

  • Explain Spring Boot's property source ordering: command line, environment variables, application.properties, defaults.
  • Mention programmatic configuration using WebServerFactoryCustomizer for dynamic port assignment at startup.
  • Discuss how to configure multiple connectors for serving HTTP and HTTPS on different ports simultaneously.

Follow-up questions to expect

  • What is the property resolution order in Spring Boot?
  • How does @LocalServerPort work in tests?
  • Can you configure Spring Boot to listen on multiple ports?
Practice this question with AI feedback →
What is the starter dependency for a Spring Boot web application?
easy

What they're really asking

The interviewer wants to confirm you know the fundamental starter for building web applications and understand what it includes.

How you'll be scored

Weak

Cannot name the correct starter or confuses it with other dependencies.

Average

Correctly names spring-boot-starter-web but does not know what it bundles.

Strong

Names the starter, lists key transitive dependencies it brings in, and explains the auto-configuration it triggers.

How to structure your answer

  1. Name the starter dependency.
  2. List what it bundles.
  3. Explain the auto-configuration it triggers.
  4. Mention the reactive alternative.

Key points to hit

  • spring-boot-starter-web is the starter for building web applications including RESTful services.
  • It bundles Spring MVC, embedded Tomcat, Jackson for JSON serialization, and Bean Validation.
  • Auto-configures DispatcherServlet, default error handling, and static resource serving.
  • For reactive web applications, spring-boot-starter-webflux is the alternative, which uses Netty instead of Tomcat.

Common mistakes

  • Confusing spring-boot-starter-web with spring-boot-starter-webflux, which uses a completely different programming model.
  • Not knowing that spring-boot-starter-web already includes an embedded server, so you do not need a separate Tomcat dependency.

Sample answer

The starter dependency for a web application is spring-boot-starter-web. You add it to your pom.xml or build.gradle, and it pulls in everything you need: Spring MVC for request handling, embedded Tomcat as the servlet container, Jackson for JSON serialization and deserialization, and Hibernate Validator for bean validation.

It also triggers auto-configuration that sets up DispatcherServlet, configures default error pages, and enables serving static resources from /static or /public directories. If you want a reactive, non-blocking web application instead, you would use spring-boot-starter-webflux, which replaces Tomcat with Netty and uses a different programming model based on reactive streams.

How to level up

  • Mention that you can swap the embedded server from Tomcat to Jetty or Undertow by excluding the Tomcat dependency and adding the alternative.
  • Explain that spring-boot-starter-web transitively includes spring-boot-starter which provides core features like auto-configuration and logging.
  • Discuss how spring-boot-starter-web and spring-boot-starter-webflux should not both be on the classpath as it causes configuration conflicts.

Follow-up questions to expect

  • How do you switch from embedded Tomcat to Jetty?
  • What is the difference between spring-boot-starter-web and spring-boot-starter-webflux?
  • What happens if both web and webflux starters are on the classpath?
Practice this question with AI feedback →

Ready to put this into practice?

Try these questions in a mock interview →

Still applying for jobs? Let Auto Apply do it

Spring Boot Auto-Configuration (Intermediate) (10)

How does Spring Boot auto-configuration work internally?
medium

What they're really asking

The interviewer wants to see if you understand the mechanism behind the magic of Spring Boot, not just that it works but how it discovers and applies configuration classes.

How you'll be scored

Weak

Says Spring Boot "automatically figures out what you need" without any understanding of the mechanism.

Average

Mentions @EnableAutoConfiguration and classpath scanning but cannot explain spring.factories or conditional annotations.

Strong

Walks through the full chain from @SpringBootApplication to META-INF/spring.factories to @Conditional annotations and explains how each step filters bean creation.

How to structure your answer

  1. Start with @SpringBootApplication which includes @EnableAutoConfiguration.
  2. Explain how Spring Boot discovers auto-configuration classes.
  3. Detail the role of @Conditional annotations in filtering.
  4. Show how you can debug and override the process.

Key points to hit

  • @EnableAutoConfiguration triggers Spring Boot to load auto-configuration classes listed in META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports (or spring.factories in older versions)
  • Each auto-configuration class uses @Conditional annotations like @ConditionalOnClass, @ConditionalOnMissingBean, and @ConditionalOnProperty to decide if it should apply.
  • @ConditionalOnMissingBean ensures your custom bean definitions take precedence over auto-configured ones.
  • Running with --debug flag prints the conditions evaluation report showing which auto-configurations were applied and which were skipped.

Common mistakes

  • Describing auto-configuration as magic without understanding the conditional evaluation mechanism.
  • Not knowing that you can override any auto-configured bean by defining your own, which is enabled by @ConditionalOnMissingBean.

Sample answer

When you use @SpringBootApplication, it includes @EnableAutoConfiguration, which tells Spring Boot to scan for auto-configuration classes. Spring Boot discovers these classes from META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports files on the classpath. Each auto-configuration class is guarded by @Conditional annotations. For example, DataSourceAutoConfiguration has @ConditionalOnClass(DataSource.class), so it only activates if a JDBC driver is on the classpath.

It also uses @ConditionalOnMissingBean, which means if you define your own DataSource bean, the auto-configured one is skipped. This is how Spring Boot provides smart defaults while always letting you override them.

I debug this by running with the --debug flag, which prints a conditions evaluation report showing exactly which configurations applied and why others were excluded.

How to level up

  • Explain the migration from spring.factories to AutoConfiguration.imports file in Spring Boot 3.x for better performance.
  • Discuss auto-configuration ordering with @AutoConfigureAfter and @AutoConfigureBefore for controlling initialization sequence.
  • Mention that you can create your own auto-configuration classes for shared libraries within your organization.

Follow-up questions to expect

  • How do you see which auto-configurations were applied to your running application?
  • What is the difference between @Conditional and @Profile?
  • How do you create a custom auto-configuration class?
Practice this question with AI feedback →
How do you disable a specific auto-configuration class?
medium

What they're really asking

This tests whether you understand Spring Boot's auto-configuration internals and can troubleshoot when default configurations conflict with custom requirements. The interviewer wants to see if you know how to selectively disable parts of the framework.

How you'll be scored

Weak

Only mentions excluding dependencies from pom.xml without understanding configuration classes.

Average

Correctly identifies @SpringBootApplication(exclude) but doesn't explain when or why to use it.

Strong

Demonstrates multiple approaches, explains the auto-configuration mechanism, and discusses production implications of disabling configurations.

How to structure your answer

  1. Explain the exclude parameter in @SpringBootApplication.
  2. Show alternative approaches using @EnableAutoConfiguration.
  3. Mention application.properties method.
  4. Explain when and why you'd disable auto-configurations.
  5. Discuss potential impacts of disabling configurations.

Key points to hit

  • Use @SpringBootApplication(exclude = {ClassName.class}) for compile-time exclusion.
  • Alternative: spring.autoconfigure.exclude property in application.properties for runtime control.
  • Understand that disabling auto-configuration may require manual bean definitions.
  • Consider excluding conflicting configurations when integrating custom implementations.

Common mistakes

  • Assuming you can disable any configuration without understanding dependencies.
  • Not realizing that excluding configurations might break other auto-configured components that depend on them.

Sample answer

There are several ways to disable specific auto-configuration classes in Spring Boot. The most common approach is using the exclude parameter in @SpringBootApplication, like @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}). Alternatively, you can use the spring.autoconfigure.exclude property in application.properties.

I typically disable auto-configurations when I need custom implementations that conflict with Spring Boot's defaults, like when integrating a custom security framework or using a specialized data access layer. You need to be careful because some auto-configurations depend on others, so excluding one might break related functionality.

How to level up

  • Use @ConditionalOnProperty to conditionally disable configurations based on environment.
  • Monitor startup logs to understand which auto-configurations are being applied or excluded.
  • Create custom auto-configuration classes that can be conditionally enabled instead of disabling existing ones.

Follow-up questions to expect

  • How would you debug which auto-configurations are being applied?
  • What happens if you exclude DataSourceAutoConfiguration but still have JPA dependencies?
  • Can you show how to create a custom auto-configuration class?
Practice this question with AI feedback →
Can you replace the embedded Tomcat server with another server (Jetty, Undertow)?
medium

What they're really asking

This tests your understanding of Spring Boot's embedded server flexibility and whether you know how to swap out core infrastructure components. The interviewer wants to see if you understand the modular nature of Spring Boot starters.

How you'll be scored

Weak

Vague mention of changing servers without specific steps or understanding of why you'd do this.

Average

Correctly explains dependency exclusion and inclusion but doesn't discuss performance or use case differences.

Strong

Demonstrates clear steps, explains server characteristics, and discusses when each server choice makes sense in production.

How to structure your answer

  1. Explain that embedded servers are just dependencies that can be swapped.
  2. Show how to exclude spring-boot-starter-tomcat.
  3. Demonstrate adding alternative server starter.
  4. Discuss server-specific characteristics and use cases.
  5. Mention any configuration differences.

Key points to hit

  • Exclude spring-boot-starter-tomcat from spring-boot-starter-web dependency.
  • Add spring-boot-starter-jetty or spring-boot-starter-undertow as replacement.
  • Each server has different performance characteristics and memory footprints.
  • Configuration properties may differ between server implementations.

Common mistakes

  • Thinking you need to change application code when switching servers.
  • Not understanding that some server-specific features might not be portable.

Sample answer

Yes, you can easily replace Tomcat with Jetty or Undertow by modifying your Maven or Gradle dependencies. First, exclude spring-boot-starter-tomcat from the spring-boot-starter-web dependency, then add spring-boot-starter-jetty or spring-boot-starter-undertow. For example, in Maven you'd exclude Tomcat in the web starter and add the Jetty starter dependency.

I've switched to Undertow in projects that needed better performance under high load, as it typically has lower memory usage and better throughput. The application code remains unchanged, but you might need to adjust server-specific configuration properties.

How to level up

  • Benchmark different servers with your specific workload to make data-driven decisions.
  • Consider Undertow for reactive applications due to its non-blocking I/O architecture.
  • Use server-specific configuration classes when you need fine-grained control over server behavior.

Follow-up questions to expect

  • What are the performance differences between Tomcat, Jetty, and Undertow?
  • How would you configure SSL differently for each embedded server?
  • Can you run multiple embedded servers in the same application?
Practice this question with AI feedback →
Can you create a non-web application in Spring Boot?
medium

What they're really asking

This tests whether you understand that Spring Boot isn't just for web applications and can recognize when the framework's dependency injection and configuration management are valuable without HTTP endpoints. The interviewer wants to see architectural flexibility.

How you'll be scored

Weak

Doesn't understand how to exclude web functionality or why you'd want a non-web Spring Boot app.

Average

Correctly mentions excluding web starter but doesn't explain compelling use cases.

Strong

Demonstrates clear implementation approaches and explains scenarios where non-web Spring Boot applications provide value over plain Java.

How to structure your answer

  1. Confirm that Spring Boot supports non-web applications.
  2. Show how to exclude web dependencies.
  3. Explain alternative application types.
  4. Provide concrete use cases.
  5. Mention lifecycle management for non-web apps.

Key points to hit

  • Set spring.main.web-application-type=NONE or use SpringApplication.setWebApplicationType()
  • Exclude spring-boot-starter-web if accidentally included.
  • Common use cases include batch processing, scheduled tasks, and command-line tools.
  • Non-web apps still benefit from dependency injection, configuration management, and auto-configuration.

Common mistakes

  • Including web dependencies unnecessarily, which starts an embedded server.
  • Not understanding how to keep a non-web application running beyond startup.

Sample answer

Absolutely, Spring Boot is excellent for non-web applications. You can create command-line tools, batch processors, or scheduled task applications. Simply don't include spring-boot-starter-web, or if you need to explicitly disable web functionality, set spring.main.web-application-type=NONE in your properties.

I've built data migration tools and ETL processors this way because you still get all the benefits of dependency injection, configuration management, and Spring Boot's auto-configuration. For applications that need to keep running, you can implement CommandLineRunner or ApplicationRunner interfaces, or use @Scheduled annotations for periodic tasks.

How to level up

  • Use @EnableScheduling for applications that need to run periodic tasks and stay alive.
  • Implement ApplicationRunner instead of CommandLineRunner when you need access to application arguments as ApplicationArguments.
  • Consider using Spring Batch starter for complex data processing workflows.

Follow-up questions to expect

  • How do you prevent a non-web Spring Boot application from shutting down immediately?
  • What's the difference between CommandLineRunner and ApplicationRunner?
  • How would you handle graceful shutdown in a long-running non-web application?
Practice this question with AI feedback →
What is Spring Boot dependency management and how does it simplify projects?
medium

What they're really asking

This tests your understanding of Spring Boot's approach to dependency management and whether you grasp how it solves version compatibility hell. The interviewer wants to see if you understand the value proposition beyond just convenience.

How you'll be scored

Weak

Only mentions that it manages versions without understanding the compatibility testing or BOM concept.

Average

Correctly explains version management but doesn't discuss the testing and compatibility aspects that make it valuable.

Strong

Demonstrates understanding of the BOM approach, compatibility testing, and how it reduces dependency conflicts in team environments.

How to structure your answer

  1. Explain the Bill of Materials (BOM) concept.
  2. Describe how Spring Boot manages transitive dependencies.
  3. Highlight compatibility testing between dependency versions.
  4. Show how it simplifies team development.
  5. Mention override capabilities when needed.

Key points to hit

  • Spring Boot provides a curated Bill of Materials that defines compatible versions.
  • Eliminates need to specify versions for most common libraries.
  • Dependencies are tested together to ensure compatibility.
  • Reduces dependency conflicts and classpath issues in team environments.

Common mistakes

  • Thinking Spring Boot dependency management locks you into specific versions permanently.
  • Not understanding that you can override versions when necessary but lose compatibility guarantees.

Sample answer

Spring Boot dependency management acts like a Bill of Materials that defines compatible, tested versions of hundreds of common libraries. When you include spring-boot-starter-parent, you inherit version definitions for Jackson, Hibernate, logging frameworks, and many others without specifying versions explicitly. This is incredibly valuable because the Spring team has tested these specific version combinations together.

I've seen projects where different developers added different versions of Jackson or SLF4J, creating runtime conflicts. Spring Boot eliminates this by providing a single, tested set of compatible versions that just work together.

How to level up

  • Use spring-boot-dependencies BOM if you can't inherit from spring-boot-starter-parent in corporate environments.
  • Check the dependency management section of your effective POM to see what versions are being managed.
  • Override managed versions sparingly and test thoroughly since you lose compatibility guarantees.

Follow-up questions to expect

  • How do you override a managed dependency version when you need a newer version?
  • What happens if you don't use Spring Boot's parent POM?
  • How can you see which versions are being managed by Spring Boot?
Practice this question with AI feedback →
What is the difference between @SpringBootApplication and @EnableAutoConfiguration?
medium

What they're really asking

This tests your understanding of Spring Boot's annotation hierarchy and whether you can distinguish between the convenience annotation and its underlying components. The interviewer wants to see if you understand what's happening under the hood.

How you'll be scored

Weak

Treats them as the same thing or can't explain what @SpringBootApplication actually includes.

Average

Correctly identifies that @SpringBootApplication includes @EnableAutoConfiguration but doesn't explain the other components or when to use each.

Strong

Explains the full composition of @SpringBootApplication and demonstrates when you'd use @EnableAutoConfiguration alone for more granular control.

How to structure your answer

  1. Define what @SpringBootApplication combines.
  2. Explain @EnableAutoConfiguration's specific role.
  3. Show the other components included in @SpringBootApplication.
  4. Discuss when to use each annotation.
  5. Provide examples of granular control scenarios.

Key points to hit

  • @SpringBootApplication combines @Configuration, @EnableAutoConfiguration, and @ComponentScan.
  • @EnableAutoConfiguration only handles auto-configuration without component scanning or configuration.
  • Use @EnableAutoConfiguration alone when you need custom component scanning or configuration strategies.
  • @SpringBootApplication provides sensible defaults for most applications.

Common mistakes

  • Thinking @EnableAutoConfiguration includes component scanning.
  • Not realizing that using @EnableAutoConfiguration alone requires manual @ComponentScan configuration.

Sample answer

@SpringBootApplication is a convenience annotation that combines three separate annotations: @Configuration, @EnableAutoConfiguration, and @ComponentScan with default packages. @EnableAutoConfiguration by itself only handles the auto-configuration mechanism, it doesn't scan for components or mark the class as a configuration class.

I use @EnableAutoConfiguration directly when I need custom component scanning strategies, like when building modular applications where I want to scan specific packages or exclude certain components. For most standard applications, @SpringBootApplication provides exactly what you need with sensible defaults.

How to level up

  • Use @EnableAutoConfiguration with custom @ComponentScan when building libraries or complex modular applications.
  • The scanBasePackages parameter in @SpringBootApplication is equivalent to @ComponentScan configuration.
  • Consider using @EnableAutoConfiguration in test configurations where you want auto-configuration but not full component scanning.

Follow-up questions to expect

  • When would you use @EnableAutoConfiguration without @ComponentScan?
  • How does the default package scanning work in @SpringBootApplication?
  • Can you exclude specific auto-configurations while using @SpringBootApplication?
Practice this question with AI feedback →
Can you disable the default web server in a Spring Boot application?
medium

What they're really asking

The interviewer is checking whether you understand that Spring Boot applications are not always web apps and that you can configure the application type for batch jobs, CLI tools, or messaging consumers.

How you'll be scored

Weak

Does not know this is possible or suggests removing the web starter as the only option.

Average

Knows about spring.main.web-application-type=none but cannot explain when or why you would do this.

Strong

Explains multiple approaches, the use cases for non-web applications, and how Spring Boot adapts its auto-configuration based on application type.

How to structure your answer

  1. Confirm that yes, you can disable the web server.
  2. Show the property-based approach.
  3. Show the programmatic approach.
  4. Explain use cases for running without a web server.

Key points to hit

  • Set spring.main.web-application-type=none in application.properties to disable the embedded web server entirely.
  • Programmatically use new SpringApplicationBuilder().web(WebApplicationType.NONE).run(args) for the same effect.
  • Removing spring-boot-starter-web from dependencies also prevents web server startup but removes all web-related classes.
  • Common use cases include batch processing jobs, message queue consumers, scheduled task runners, and CLI tools.

Common mistakes

  • Thinking every Spring Boot application must be a web application when the framework supports multiple application types.
  • Removing the web starter when you still need some web classes like RestTemplate, instead of just disabling the server.

Sample answer

Yes, you can disable the web server by setting spring.main.web-application-type=none in your application.properties. This tells Spring Boot to skip embedded server auto-configuration entirely while keeping the rest of the application context. You can also do it programmatically with SpringApplicationBuilder using WebApplicationType.NONE.

I have used this for batch processing applications that read from a message queue and write to a database. They need Spring's dependency injection, transaction management, and data access, but they have no HTTP endpoints.

The application still starts a full Spring context, runs any CommandLineRunner or ApplicationRunner beans, and stays alive as long as there are non-daemon threads. Alternatively, removing spring-boot-starter-web also prevents server startup, but that also removes web classes you might need as a client.

How to level up

  • Mention WebApplicationType.REACTIVE as the third option for reactive server applications.
  • Explain that Spring Boot auto-detects the application type based on classpath contents but you can override it explicitly.
  • Discuss how Actuator endpoints can still be exposed over JMX even when the web server is disabled.

Follow-up questions to expect

  • How does Spring Boot determine the default web application type?
  • Can you still use RestTemplate in a non-web application?
  • How do you keep a non-web Spring Boot application running?
Practice this question with AI feedback →
What are Spring Boot DevTools and what do they provide?
medium

What they're really asking

The interviewer wants to know if you use developer productivity tools and understand how DevTools accelerates the development feedback loop.

How you'll be scored

Weak

Has heard of DevTools but cannot explain specific features or how they work.

Average

Correctly mentions automatic restart and live reload but misses the classpath monitoring mechanism or the development-only nature.

Strong

Explains automatic restart with dual classloaders, LiveReload integration, property defaults, and the safety mechanism that disables DevTools in production.

How to structure your answer

  1. Define DevTools as a development-time productivity module.
  2. Explain the automatic restart mechanism.
  3. Cover LiveReload and property defaults.
  4. Emphasize that DevTools is automatically disabled in production.

Key points to hit

  • spring-boot-devtools provides automatic application restart when classpath files change, using a dual classloader strategy for fast restarts.
  • Uses two classloaders: a base classloader for third-party JARs that stays loaded, and a restart classloader for your code that gets recreated on changes.
  • Integrates with LiveReload to automatically refresh browsers when resources change.
  • Automatically disabled when running from a packaged JAR or when launched with a production profile, so it never affects production.

Common mistakes

  • Leaving DevTools in production dependencies when it should be scoped to development only (though Spring Boot auto-disables it)
  • Confusing DevTools restart with hot-swap tools like JRebel, which operate at a different level.

Sample answer

Spring Boot DevTools is a module you add as a development-time dependency that accelerates the coding feedback loop. Its main feature is automatic restart. When you save a file, DevTools detects the classpath change and restarts the application.

It does this efficiently using two classloaders: one for your code that gets recreated quickly, and one for third-party libraries that stays loaded. This makes restarts much faster than a full cold start. It also integrates with LiveReload so your browser refreshes automatically when templates or static resources change.

DevTools sets sensible development defaults like disabling template caching so you see changes immediately. The best part is that it automatically disables itself when you run a packaged JAR, so there is zero risk of it affecting production performance.

How to level up

  • Mention that DevTools supports remote development by triggering restarts on a remote server when local files change.
  • Discuss trigger files that let you control exactly when a restart happens instead of on every file save.
  • Explain how to exclude specific paths from triggering restarts using spring.devtools.restart.exclude.

Follow-up questions to expect

  • How does DevTools know when to restart the application?
  • What is the difference between DevTools restart and JRebel hot-swap?
  • How do you prevent DevTools from being included in a production build?
Practice this question with AI feedback →
What is the difference between WAR deployment and embedded containers?
medium

What they're really asking

The interviewer wants to see if you understand modern deployment strategies versus traditional Java EE deployment and can articulate why Spring Boot defaults to embedded containers.

How you'll be scored

Weak

Does not clearly understand the difference between an external application server and an embedded container.

Average

Correctly describes both approaches but does not explain the advantages and disadvantages of each or when you would choose one.

Strong

Explains both deployment models, their trade-offs, and can articulate why embedded containers align with modern microservices and containerized deployments.

How to structure your answer

  1. Explain traditional WAR deployment to an external application server.
  2. Explain embedded container approach with executable JARs.
  3. Compare the advantages and disadvantages.
  4. Recommend when to use each approach.

Key points to hit

  • WAR deployment packages your app as a .war file deployed to an external server like Tomcat, WildFly, or WebLogic, where the server manages the servlet lifecycle.
  • Embedded containers package the server inside your JAR so the application starts with java -jar, owning its own server lifecycle.
  • Embedded containers simplify containerization with Docker, CI/CD pipelines, and cloud deployments because each app is self-contained.
  • WAR deployment is still used in enterprises with existing application server infrastructure or when multiple apps share a single server instance.

Common mistakes

  • Claiming WAR deployment is obsolete when many enterprises still require it for compliance or infrastructure reasons.
  • Not knowing that Spring Boot supports both approaches and that switching requires extending SpringBootServletInitializer.

Sample answer

WAR deployment is the traditional Java EE approach where you package your application as a .war file and deploy it to an external Tomcat, WildFly, or WebLogic server. The server owns the lifecycle, manages the servlet container, and you deploy through a management console or deployment directory. Embedded containers are the Spring Boot default.

The server is packaged inside your application JAR, and you start everything with java -jar app.jar. This makes each application self-contained, which is perfect for Docker containers, Kubernetes deployments, and CI/CD pipelines because you do not need to install and configure an external server.

In my experience, embedded containers are the right choice for new microservices. WAR deployment makes sense when you are integrating into an existing enterprise infrastructure that mandates a shared application server. Spring Boot supports both. For WAR, you extend SpringBootServletInitializer and change the packaging in your build file.

How to level up

  • Mention that with WAR deployment you can still use Spring Boot features, but some auto-configuration behaves differently in an external container.
  • Discuss how embedded containers simplify horizontal scaling since each instance is independent.
  • Explain that the same Spring Boot app can be configured to produce both a runnable JAR and a deployable WAR simultaneously.

Follow-up questions to expect

  • How do you convert a Spring Boot application from JAR to WAR packaging?
  • What changes when you deploy a Spring Boot WAR to an external Tomcat?
  • How does embedded container deployment work with Docker?
Practice this question with AI feedback →
Where do you define properties in a Spring Boot application?
medium

What they're really asking

The interviewer wants to verify you understand Spring Boot's externalized configuration system and the property source hierarchy, which is essential for managing settings across environments.

How you'll be scored

Weak

Only knows about application.properties and nothing else.

Average

Mentions application.properties and application.yml but does not understand the property source precedence or environment-specific profiles.

Strong

Explains the full property source hierarchy, profile-specific files, environment variables, command-line arguments, and the precedence order that determines which value wins.

How to structure your answer

  1. List the primary property sources in Spring Boot.
  2. Explain the precedence order.
  3. Discuss profile-specific properties.
  4. Mention externalized configuration for production environments.

Key points to hit

  • application.properties or application.yml in src/main/resources is the primary property file.
  • Profile-specific files like application-dev.properties or application-prod.yml override the base file for their active profile.
  • Environment variables and command-line arguments override file-based properties, with command-line having the highest precedence.
  • Spring Boot supports 17+ property sources with a defined precedence order documented in the reference guide.

Common mistakes

  • Hardcoding environment-specific values in application.properties instead of using profiles or environment variables.
  • Not understanding that command-line arguments override everything, which is important for debugging unexpected configuration behavior.

Sample answer

Spring Boot supports many property sources with a clear precedence order. The most common place is application.properties or application.yml in your src/main/resources directory. For environment-specific configuration, I create profile-specific files like application-dev.yml and application-prod.yml, then activate the right profile with spring.profiles.active. These override the base properties for their environment.

Beyond files, you can set properties through environment variables like SPRING_DATASOURCE_URL, which is what I use in Kubernetes deployments. Command-line arguments with -- prefix have even higher precedence. In production, I typically keep sensitive values like database passwords in environment variables or a config server, while application-level defaults live in the base properties file.

The full precedence order has 17 levels, but the key thing to remember is: command line beats environment variables, which beat profile-specific files, which beat the base properties file.

How to level up

  • Mention Spring Cloud Config Server for centralized configuration management across multiple microservices.
  • Discuss @PropertySource for loading custom property files beyond the standard locations.
  • Explain config tree support for Kubernetes secrets mounted as files, which Spring Boot 2.4+ can read natively.

Follow-up questions to expect

  • How do you activate a specific profile in Spring Boot?
  • What is the full property source precedence order?
  • How do you manage secrets in production without putting them in property files?
Practice this question with AI feedback →

Spring Boot Auto-Configuration (Advanced) (5)

How do you create a custom Spring Boot starter?
hard

What they're really asking

The interviewer wants to see if you have deep enough understanding of Spring Boot internals to extend its ecosystem, which indicates senior-level knowledge of auto-configuration, conditional beans, and dependency management.

How you'll be scored

Weak

Cannot describe the structure or key components needed for a custom starter.

Average

Knows you need an auto-configuration class and a spring.factories file but misses the two-module convention or conditional annotations.

Strong

Explains the two-module pattern, auto-configuration class with @Conditional annotations, META-INF registration, and @ConfigurationProperties for user-facing configuration.

How to structure your answer

  1. Explain the two-module convention: autoconfigure module and starter module.
  2. Detail the auto-configuration class with conditional annotations.
  3. Show how to register it in META-INF for discovery.
  4. Add user-facing configuration with @ConfigurationProperties.

Key points to hit

  • Follow the two-module convention: an autoconfigure module with the logic and a starter module that is just a dependency aggregator.
  • The auto-configuration class uses @AutoConfiguration and @Conditional annotations to create beans only when conditions are met.
  • Register the auto-configuration class in META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports.
  • Provide @ConfigurationProperties for type-safe user configuration and include spring-boot-configuration-processor for IDE metadata generation.

Common mistakes

  • Creating a single module instead of following the two-module convention, which mixes auto-configuration logic with the dependency descriptor.
  • Forgetting @ConditionalOnMissingBean, which prevents your starter from overriding custom beans that users define themselves.

Sample answer

Creating a custom starter follows a two-module convention. The first module, named something like my-spring-boot-autoconfigure, contains your auto-configuration class annotated with @AutoConfiguration. Inside this class, I use @ConditionalOnClass to check that required libraries are on the classpath, @ConditionalOnMissingBean to ensure I do not override any beans the user defines, and @EnableConfigurationProperties to bind user-facing configuration.

I register the class in META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports so Spring Boot discovers it. The second module, my-spring-boot-starter, is just a pom.xml that depends on the autoconfigure module and any required third-party libraries. Users add only the starter to their project and get everything auto-configured.

I also add the spring-boot-configuration-processor dependency so IDEs show autocompletion for the custom properties.

How to level up

  • Mention using @AutoConfigureAfter and @AutoConfigureBefore to control ordering relative to other auto-configuration classes.
  • Discuss generating additional-spring-configuration-metadata.json for custom property hints and deprecation notices in IDEs.
  • Explain how to write integration tests for your starter using @SpringBootTest with test-specific configurations.

Follow-up questions to expect

  • Why does Spring Boot recommend the two-module structure for custom starters?
  • How do you test a custom starter before publishing it?
  • How do you handle backward compatibility when updating a custom starter?
Practice this question with AI feedback →
How do you create a custom auto-configuration class?
hard

What they're really asking

This tests your understanding of Spring Boot's extensibility mechanism and whether you can create reusable components that follow Spring Boot's convention-over-configuration philosophy.

How you'll be scored

Weak

Mentions @Configuration without understanding conditional logic or auto-configuration registration mechanisms.

Average

Correctly explains @EnableAutoConfiguration and basic conditional annotations but lacks details on registration process.

Strong

Demonstrates complete understanding of the registration mechanism, conditional logic, and can explain when custom auto-configuration is appropriate versus other Spring patterns.

How to structure your answer

  1. Create @Configuration class with @EnableAutoConfiguration.
  2. Add conditional annotations to control when it applies.
  3. Register the configuration in META-INF files.
  4. Explain the auto-configuration ordering.
  5. Discuss testing and debugging strategies.

Key points to hit

  • Auto-configuration classes use @Configuration with conditional annotations to decide when to activate.
  • Registration happens through META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports in Spring Boot 2.7+.
  • @ConditionalOnClass and @ConditionalOnMissingBean prevent conflicts with user configurations.
  • Use @AutoConfigureOrder or @AutoConfigureBefore/@AutoConfigureAfter for proper initialization sequence.

Common mistakes

  • Forgetting to register the auto-configuration class in META-INF files, making it invisible to Spring Boot.
  • Not using @ConditionalOnMissingBean, which prevents users from overriding your defaults.

Sample answer

I create a @Configuration class annotated with @EnableAutoConfiguration and add conditional annotations like @ConditionalOnClass to ensure it only activates when specific classes are on the classpath. For example, @ConditionalOnClass(DataSource.class) would only trigger if a database driver is present. I use @ConditionalOnMissingBean to allow users to override my defaults by providing their own beans.

The key step is registering the configuration in META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports so Spring Boot can discover it during startup. I also consider ordering with @AutoConfigureBefore if my configuration needs to run before other auto-configurations.

How to level up

  • Use @ConfigurationProperties for type-safe configuration binding instead of multiple @Value annotations.
  • Consider creating a custom starter module that bundles your auto-configuration with required dependencies.
  • Implement EnvironmentPostProcessor if you need to modify the environment before auto-configuration runs.

Follow-up questions to expect

  • How would you debug why your auto-configuration isn't activating?
  • What's the difference between @ConditionalOnBean and @ConditionalOnMissingBean?
  • How do you handle circular dependencies in auto-configuration?
Practice this question with AI feedback →
Explain the role of spring.factories (or META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports).
hard

What they're really asking

This tests your knowledge of Spring Boot's discovery mechanism evolution and whether you understand how the framework finds and loads auto-configurations.

How you'll be scored

Weak

Confuses spring.factories with other Spring configuration mechanisms or doesn't know about the newer imports file.

Average

Correctly explains either spring.factories or the newer imports mechanism but doesn't understand the migration or why it changed.

Strong

Explains both mechanisms, understands the Spring Boot 2.7+ migration to imports files, and can discuss the performance and maintainability benefits of the change.

How to structure your answer

  1. Explain the original spring.factories mechanism.
  2. Describe the newer AutoConfiguration.imports file approach.
  3. Compare the two approaches and explain the migration.
  4. Discuss how Spring Boot processes these files during startup.
  5. Cover debugging and troubleshooting registration issues.

Key points to hit

  • spring.factories was the original mechanism using key-value pairs to register auto-configurations.
  • Spring Boot 2.7+ introduced META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports for simpler one-class-per-line format.
  • The imports file provides better IDE support and faster parsing compared to properties format.
  • Both files serve as the discovery mechanism that tells Spring Boot which auto-configuration classes to consider during startup.

Common mistakes

  • Using the old spring.factories format in new projects when AutoConfiguration.imports is preferred.
  • Not understanding that these files only register candidates, conditional annotations determine actual activation.

Sample answer

Originally, Spring Boot used META-INF/spring.factories with key-value pairs where the key was org.springframework.boot.autoconfigure.EnableAutoConfiguration and values were comma-separated auto-configuration class names. Starting with Spring Boot 2.7, they introduced META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports which lists one auto-configuration class per line. This newer format is cleaner, provides better IDE support, and parses faster.

Both files serve the same purpose of telling Spring Boot which auto-configuration classes to consider, but the conditional annotations on those classes determine if they actually activate. The migration improves maintainability and reduces the chance of syntax errors in large auto-configuration lists.

How to level up

  • Use spring-boot-autoconfigure-processor to generate metadata that helps IDEs provide better autocomplete for configuration properties.
  • Check the ConditionEvaluationReport to see which auto-configurations were considered and why they were or weren't applied.
  • Consider that spring.factories is still used for other extension points like ApplicationListener and EnvironmentPostProcessor.

Follow-up questions to expect

  • How can you see which auto-configurations are being applied in your application?
  • What other extension points still use spring.factories?
  • How do you handle auto-configuration conflicts between different libraries?
Practice this question with AI feedback →
How do conditional annotations (@ConditionalOnClass, @ConditionalOnProperty, etc.) work?
hard

What they're really asking

This tests your understanding of Spring Boot's conditional logic system and whether you can implement smart auto-configuration that activates only when appropriate.

How you'll be scored

Weak

Lists conditional annotations without explaining their logic or when to use each one.

Average

Correctly explains a few conditional annotations with basic examples but lacks depth on evaluation order and combining conditions.

Strong

Demonstrates comprehensive understanding of conditional evaluation, can explain when to use each annotation type, and understands how Spring Boot processes multiple conditions together.

How to structure your answer

  1. Explain the conditional annotation concept and evaluation timing.
  2. Cover the main conditional annotation types with examples.
  3. Describe how multiple conditions are combined.
  4. Explain condition evaluation order and short-circuiting.
  5. Discuss debugging conditional logic and common patterns.

Key points to hit

  • Conditional annotations are evaluated during the configuration phase to determine if a @Configuration class or @Bean method should be processed.
  • @ConditionalOnClass checks classpath presence, @ConditionalOnProperty reads configuration values, @ConditionalOnMissingBean prevents duplicate beans.
  • Multiple conditions use AND logic by default, all must be true for the configuration to activate.
  • Spring Boot evaluates conditions in a specific order, with class-level conditions checked before method-level ones for performance.

Common mistakes

  • Assuming conditions are re-evaluated at runtime, they're only checked once during application startup.
  • Not understanding that @ConditionalOnMissingBean looks at the bean definition time, not the final application context.

Sample answer

Conditional annotations control when Spring Boot applies auto-configurations by evaluating conditions during startup. @ConditionalOnClass(DataSource.class) checks if a class exists on the classpath, while @ConditionalOnProperty(name='app.feature.enabled', havingValue='true') reads from application properties. @ConditionalOnMissingBean ensures your configuration only provides defaults when the user hasn't defined their own bean.

These conditions are evaluated once during the configuration phase using AND logic, so all conditions must be true. Spring Boot processes class-level conditions first for performance, then method-level ones. I can debug condition evaluation using the ConditionEvaluationReport to see exactly why configurations were included or excluded.

How to level up

  • Use @ConditionalOnWebApplication(type = Type.SERVLET) to differentiate between servlet and reactive web applications.
  • Combine @ConditionalOnProperty with matchIfMissing=true to make features opt-out rather than opt-in.
  • Create custom conditional annotations by implementing the Condition interface for complex business logic.

Follow-up questions to expect

  • What's the difference between @ConditionalOnBean and @ConditionalOnMissingBean evaluation timing?
  • How would you create a custom conditional annotation?
  • What happens when you have conflicting conditional logic in different auto-configurations?
Practice this question with AI feedback →
How do you deploy a Spring Boot application to an external server?
hard

What they're really asking

This tests your understanding of Spring Boot deployment options and whether you know how to adapt the framework's embedded server approach for traditional enterprise environments.

How you'll be scored

Weak

Suggests only copying the JAR file without understanding WAR packaging or servlet container requirements.

Average

Knows about WAR packaging and SpringBootServletInitializer but lacks details on configuration changes needed for external containers.

Strong

Explains the complete WAR deployment process, understands the trade-offs between embedded and external servers, and can discuss environment-specific configuration strategies.

How to structure your answer

  1. Explain the difference between embedded and external server deployment.
  2. Detail the WAR packaging configuration changes needed.
  3. Cover the SpringBootServletInitializer requirement.
  4. Discuss environment-specific configuration strategies.
  5. Address common deployment challenges and solutions.

Key points to hit

  • Change packaging from 'jar' to 'war' in Maven/Gradle and mark embedded server dependencies as provided scope.
  • Extend SpringBootServletInitializer in your main application class to bridge Spring Boot with servlet container lifecycle.
  • External containers handle server configuration, so remove embedded server properties from application.properties.
  • Use Spring profiles and external configuration to manage environment-specific settings without code changes.

Common mistakes

  • Forgetting to mark embedded Tomcat as provided scope, causing class conflicts in the external container.
  • Not understanding that server properties like server.port are ignored in WAR deployments since the external container controls these settings.

Sample answer

To deploy to an external server, I first change the packaging in my build file from 'jar' to 'war' and mark the embedded Tomcat dependency as provided scope to avoid conflicts. Then I make my main application class extend SpringBootServletInitializer and override the configure method to return the application sources.

This bridges Spring Boot's auto-configuration with the servlet container's lifecycle. I remove server-specific properties like server.port from application.properties since the external container manages these. For environment-specific configuration, I use Spring profiles and external property files so the same WAR can be deployed across different environments without rebuilding.

How to level up

  • Use Maven profiles or Gradle build variants to create both JAR and WAR artifacts from the same codebase.
  • Consider that external containers may have different classloader hierarchies that affect dependency resolution.
  • Implement custom health checks that work with both embedded and external container monitoring.

Follow-up questions to expect

  • What are the trade-offs between embedded and external server deployment?
  • How do you handle database connection pools differently in external containers?
  • What security considerations change when deploying to external servers?
Practice this question with AI feedback →

Ready to put this into practice?

Try these questions in a mock interview →

Still applying for jobs? Let Auto Apply do it

Spring MVC & REST APIs (Beginner) (5)

What is Spring MVC?
easy

What they're really asking

This tests your foundational understanding of Spring's web framework and whether you grasp the MVC pattern implementation that underlies Spring Boot's web capabilities.

How you'll be scored

Weak

Gives a generic MVC definition without connecting it to Spring-specific components or request handling flow.

Average

Correctly identifies the main Spring MVC components like DispatcherServlet and controllers but lacks detail on the request processing lifecycle.

Strong

Explains the complete request flow through Spring MVC components, understands the role of DispatcherServlet as the front controller, and can connect this to Spring Boot's auto-configuration benefits.

How to structure your answer

  1. Define Spring MVC as Spring's web framework implementing the Model-View-Controller pattern.
  2. Explain the role of DispatcherServlet as the central request dispatcher.
  3. Describe the main components: controllers, view resolvers, and model.
  4. Walk through the request processing flow.
  5. Connect to Spring Boot's auto-configuration advantages.

Key points to hit

  • Spring MVC is Spring Framework's web module that implements the Model-View-Controller design pattern for building web applications.
  • DispatcherServlet acts as the front controller, receiving all HTTP requests and dispatching them to appropriate handlers.
  • Controllers handle business logic and return model data, while view resolvers determine how to render responses.
  • Spring Boot auto-configures Spring MVC with sensible defaults, eliminating most XML configuration.

Common mistakes

  • Confusing Spring MVC with Spring Boot, they're related but Spring MVC is the underlying web framework while Spring Boot provides auto-configuration on top.

Sample answer

Spring MVC is Spring Framework's web module that implements the Model-View-Controller design pattern for building web applications. The core component is DispatcherServlet, which acts as a front controller receiving all HTTP requests and routing them to appropriate handler methods in controller classes. Controllers contain the business logic and return model data along with view information.

View resolvers then determine how to render the response, whether as JSON, HTML templates, or other formats. Spring Boot builds on this by auto-configuring Spring MVC with embedded servers and sensible defaults, so I can start building REST APIs immediately without XML configuration.

How to level up

  • Understand that @RestController is a specialized @Controller that combines @Controller with @ResponseBody for REST APIs.
  • Learn about HandlerInterceptors for cross-cutting concerns like logging and authentication that apply to multiple controllers.
  • Explore Spring WebFlux as an alternative reactive web framework when you need non-blocking I/O.

Follow-up questions to expect

  • What's the difference between @Controller and @RestController?
  • How does Spring MVC handle different content types in requests and responses?
  • What are HandlerInterceptors and when would you use them?
Practice this question with AI feedback →
What is the @RestController annotation?
easy

What they're really asking

This tests basic Spring Boot annotation knowledge and whether you understand the purpose of specialized controller annotations. The interviewer wants to see if you grasp how Spring Boot simplifies REST API development through convention over configuration.

How you'll be scored

Weak

Only mentions that @RestController is for REST APIs without explaining what it actually does.

Average

Correctly identifies it as a combination of @Controller and @ResponseBody with a basic example.

Strong

Explains the annotation's purpose, mentions the combination of annotations, and discusses when to use it versus alternatives.

How to structure your answer

  1. Define what @RestController is and its core purpose.
  2. Explain which annotations it combines.
  3. Provide a concrete code example.
  4. Mention when to use it versus @Controller.

Key points to hit

  • @RestController combines @Controller and @ResponseBody annotations.
  • Automatically serializes return values to JSON/XML without explicit @ResponseBody on each method.
  • Designed specifically for RESTful web services, not traditional MVC views.
  • Spring Boot's convention over configuration reduces boilerplate for API development.

Common mistakes

  • Confusing @RestController with @Controller and not explaining the automatic response body binding.
  • Not mentioning that it eliminates the need for @ResponseBody on individual methods.

Sample answer

@RestController is a specialized Spring annotation that combines @Controller and @ResponseBody. It tells Spring that this class handles HTTP requests and automatically converts method return values to JSON or XML responses.

For example, when I return a User object from a method, Spring Boot automatically serializes it to JSON without me needing to add @ResponseBody to every method. I use @RestController when building REST APIs, and stick with @Controller when I need to return view names for traditional MVC applications.

How to level up

  • Mention that @RestController is a composed annotation, showing understanding of Spring's meta-annotation feature.
  • Discuss content negotiation and how Spring Boot handles Accept headers automatically with @RestController.

Follow-up questions to expect

  • How does Spring Boot determine whether to serialize to JSON or XML?
  • What happens if you mix @RestController with view-based responses?
  • Can you customize the serialization behavior for @RestController methods?
Practice this question with AI feedback →
What is the difference between @Controller and @RestController?
easy

What they're really asking

This tests whether you understand the practical differences between controller types in Spring Boot applications. The interviewer wants to see if you can choose the right annotation based on application architecture needs.

How you'll be scored

Weak

States they're different but can't explain the specific differences or use cases.

Average

Correctly explains that @Controller returns views while @RestController returns data, with basic examples.

Strong

Demonstrates clear understanding of both annotations, their use cases, and mentions the @ResponseBody distinction with practical scenarios.

How to structure your answer

  1. Explain what @Controller is designed for.
  2. Explain what @RestController is designed for.
  3. Highlight the @ResponseBody difference.
  4. Provide use case scenarios for each.

Key points to hit

  • @Controller is for traditional MVC applications that return view names (JSP, Thymeleaf templates)
  • @RestController is for REST APIs that return data directly (JSON, XML)
  • @Controller requires explicit @ResponseBody annotation to return data instead of view names.
  • @RestController automatically applies @ResponseBody to all methods.

Common mistakes

  • Thinking they're interchangeable or that @RestController is just a newer version of @Controller.
  • Not understanding that @Controller methods return view names by default, not data.

Sample answer

@Controller is used for traditional MVC applications where methods return view names that get resolved to templates like Thymeleaf or JSP. @RestController is specifically for REST APIs where methods return data that gets automatically serialized to JSON or XML.

The key difference is that @Controller methods return view names by default, so if I want to return JSON data, I need to add @ResponseBody to each method. @RestController automatically includes @ResponseBody, so every method returns data directly.

I use @Controller when building web applications with server-side rendering and @RestController when building APIs for SPAs or mobile apps.

How to level up

  • Mention that you can mix both approaches in the same application, using @Controller for some endpoints and @RestController for others.
  • Discuss how Spring Boot's auto-configuration sets up different message converters based on which annotations you use.

Follow-up questions to expect

  • Can you use @ResponseBody with individual methods in a @Controller class?
  • What happens if you try to return a view name from a @RestController method?
  • How would you handle both API endpoints and web pages in the same Spring Boot application?
Practice this question with AI feedback →
What is the difference between @RequestMapping and @GetMapping?
easy

What they're really asking

This tests your understanding of Spring Boot's specialized HTTP mapping annotations and whether you recognize how they improve code readability. The interviewer wants to see if you appreciate Spring Boot's approach to reducing boilerplate code.

How you'll be scored

Weak

Can't explain the difference or thinks they're the same annotation.

Average

Correctly states that @GetMapping is specific to GET requests while @RequestMapping is generic.

Strong

Explains the specificity difference, mentions code readability benefits, and shows understanding of other HTTP method-specific annotations.

How to structure your answer

  1. Define @RequestMapping as the generic annotation.
  2. Explain @GetMapping as a specialized version.
  3. Show the code difference with examples.
  4. Mention other HTTP method-specific annotations.

Key points to hit

  • @RequestMapping is generic and can handle any HTTP method when specified.
  • @GetMapping is a specialized annotation that only handles GET requests.
  • @GetMapping is equivalent to @RequestMapping(method = RequestMethod.GET)
  • Spring Boot provides similar annotations for POST, PUT, DELETE, and PATCH.

Common mistakes

  • Thinking @GetMapping can handle multiple HTTP methods.
  • Not understanding that @RequestMapping without a method attribute accepts all HTTP methods.

Sample answer

@RequestMapping is the generic annotation that can handle any HTTP method when you specify the method attribute, like @RequestMapping(value = '/users', method = RequestMethod.GET). @GetMapping is a specialized annotation that only handles GET requests and is equivalent to that longer syntax. So @GetMapping('/users') is cleaner and more readable than the full @RequestMapping version.

Spring Boot provides similar shortcuts like @PostMapping, @PutMapping, and @DeleteMapping. I prefer using the specific annotations because they make the code more explicit about which HTTP methods each endpoint handles, and it's less typing.

How to level up

  • Mention that the specific annotations are composed annotations, showing understanding of Spring's meta-annotation capabilities.
  • Discuss how using specific annotations makes your API documentation clearer when using tools like Swagger.

Follow-up questions to expect

  • What other HTTP method-specific annotations does Spring Boot provide?
  • Can you combine @RequestMapping at the class level with @GetMapping at the method level?
  • What happens if you don't specify any HTTP method in @RequestMapping?
Practice this question with AI feedback →
Describe the flow of an HTTP request through a Spring Boot application.
easy

What they're really asking

This tests your understanding of Spring Boot's request processing architecture and the MVC pattern implementation. The interviewer wants to see if you understand how HTTP requests flow through the framework's components.

How you'll be scored

Weak

Provides a vague or incorrect sequence without mentioning key components like DispatcherServlet.

Average

Lists the main components (DispatcherServlet, Controller, View) in roughly the correct order.

Strong

Provides a detailed flow including DispatcherServlet, HandlerMapping, Controller, ViewResolver with understanding of each step's purpose.

How to structure your answer

  1. Start with the HTTP request arriving at the embedded server.
  2. Explain DispatcherServlet's role as the front controller.
  3. Describe handler mapping and method resolution.
  4. Cover controller execution and response generation.
  5. Mention view resolution for non-REST endpoints.

Key points to hit

  • Embedded Tomcat receives the HTTP request and forwards to DispatcherServlet.
  • DispatcherServlet acts as front controller and consults HandlerMapping to find the appropriate controller.
  • Controller method executes business logic and returns response data or view name.
  • For @RestController, response is serialized directly; for @Controller, ViewResolver processes view names.

Common mistakes

  • Skipping DispatcherServlet entirely or not understanding its central role.
  • Confusing the order of operations or missing key steps like HandlerMapping.

Sample answer

When an HTTP request hits a Spring Boot application, it first reaches the embedded Tomcat server, which forwards it to Spring's DispatcherServlet. The DispatcherServlet acts as a front controller and consults HandlerMapping to determine which controller method should handle the request based on the URL pattern and HTTP method.

Once it finds the right controller, it invokes the method, which executes the business logic. For @RestController methods, the return value gets automatically serialized to JSON and sent back as the HTTP response. For @Controller methods returning view names, the ViewResolver kicks in to render the appropriate template.

The final response flows back through the same path to the client.

How to level up

  • Mention interceptors and how they can intercept requests before and after controller execution.
  • Discuss how Spring Boot's auto-configuration sets up the DispatcherServlet automatically, unlike traditional Spring MVC.

Follow-up questions to expect

  • What role do HandlerInterceptors play in this request flow?
  • How does Spring Boot's embedded server setup differ from deploying to an external Tomcat?
  • Where does exception handling fit into this request processing flow?
Practice this question with AI feedback →

Spring MVC & REST APIs (Intermediate) (12)

What is the DispatcherServlet and how does it work?
medium

What they're really asking

This tests your understanding of Spring Boot's core MVC architecture and whether you grasp how the front controller pattern works. The interviewer wants to see if you understand the central component that makes Spring MVC work.

How you'll be scored

Weak

Can't explain what DispatcherServlet does or confuses it with other components.

Average

Correctly identifies it as the front controller that routes requests to appropriate handlers.

Strong

Explains the front controller pattern, describes the request delegation process, and mentions how Spring Boot configures it automatically.

How to structure your answer

  1. Define DispatcherServlet as Spring's front controller.
  2. Explain the front controller pattern benefits.
  3. Describe how it delegates requests to handlers.
  4. Mention Spring Boot's automatic configuration.
  5. Cover its role in the overall MVC architecture.

Key points to hit

  • DispatcherServlet implements the front controller pattern, providing a single entry point for all requests.
  • It delegates requests to appropriate handlers based on HandlerMapping configuration.
  • Manages the entire request lifecycle including handler execution, view resolution, and exception handling.
  • Spring Boot automatically configures DispatcherServlet, unlike traditional Spring MVC requiring web.xml configuration.

Common mistakes

  • Confusing DispatcherServlet with regular servlets or thinking it's the same as a controller.
  • Not understanding that it coordinates multiple components rather than handling business logic directly.

Sample answer

DispatcherServlet is Spring's implementation of the front controller pattern. It acts as a single entry point for all HTTP requests in a Spring Boot application and coordinates the entire request processing workflow.

When a request arrives, DispatcherServlet consults its HandlerMapping to determine which controller method should handle it, then delegates the actual processing to that controller. After the controller executes, DispatcherServlet manages view resolution for traditional MVC responses or handles serialization for REST APIs.

The beauty of Spring Boot is that it automatically configures the DispatcherServlet for you, whereas in traditional Spring MVC, you had to set it up manually in web.xml.

How to level up

  • Mention that DispatcherServlet has its own ApplicationContext, creating a parent-child context hierarchy.
  • Discuss how you can customize DispatcherServlet behavior through DispatcherServletAutoConfiguration properties in Spring Boot.

Follow-up questions to expect

  • How does DispatcherServlet determine which HandlerMapping to use when multiple are configured?
  • What's the difference between DispatcherServlet's context and the root ApplicationContext?
  • How would you configure multiple DispatcherServlet instances in a single Spring Boot application?
Practice this question with AI feedback →
What is the difference between @RequestParam, @PathVariable, and @RequestBody?
medium

What they're really asking

The interviewer wants to verify you understand how Spring MVC extracts data from different parts of an HTTP request and can choose the right annotation for each use case.

How you'll be scored

Weak

Confuses the three annotations or cannot explain where each extracts data from.

Average

Correctly explains each annotation but does not discuss optional parameters, default values, or validation.

Strong

Clearly differentiates all three, explains their configuration options, and gives REST API design examples showing when to use each.

How to structure your answer

  1. Define each annotation and where it extracts data from.
  2. Give URL and request examples for each.
  3. Discuss configuration options like required and defaultValue.
  4. Explain REST API design conventions for using each.

Key points to hit

  • @RequestParam extracts query string parameters from the URL like /search?q=spring and maps them to method parameters.
  • @PathVariable extracts values from URI path segments like /users/{id} and maps them to method parameters.
  • @RequestBody deserializes the entire HTTP request body, typically JSON, into a Java object using Jackson.
  • @RequestParam is for filtering and optional parameters, @PathVariable is for resource identifiers, and @RequestBody is for complex input in POST and PUT requests.

Common mistakes

  • Using @RequestParam for resource identifiers in the URL path when @PathVariable is the correct choice for RESTful design.
  • Not knowing that @RequestParam parameters are required by default and will cause a 400 error if missing.

Sample answer

These three annotations extract data from different parts of an HTTP request. @RequestParam pulls values from query string parameters. If my endpoint is GET /api/users?role=admin&page=2, I use @RequestParam String role and @RequestParam int page. @PathVariable extracts values from the URI path template.

For GET /api/users/42, I define @GetMapping("/users/{id}") and use @PathVariable Long id. @RequestBody deserializes the entire request body into a Java object. For POST /api/users with a JSON body, I use @RequestBody CreateUserRequest request and Spring uses Jackson to convert the JSON.

In REST API design, I follow the convention of @PathVariable for resource identifiers, @RequestParam for filtering and pagination, and @RequestBody for create and update payloads.

How to level up

  • Mention that @RequestParam supports required=false and defaultValue for optional parameters.
  • Discuss how @RequestBody works with @Valid for automatic input validation with error responses.
  • Explain that @PathVariable names must match the URI template variable names, or use the value attribute for explicit mapping.

Follow-up questions to expect

  • How do you handle optional request parameters?
  • How does @RequestBody handle nested JSON objects?
  • What happens if @PathVariable does not match a URI template variable?
Practice this question with AI feedback →
What is the @ResponseBody annotation?
medium

What they're really asking

The interviewer wants to see if you understand how Spring MVC serializes return values to HTTP response bodies and how @RestController simplifies this for REST APIs.

How you'll be scored

Weak

Cannot explain what @ResponseBody does or confuses it with @RequestBody.

Average

Correctly explains that it writes the return value to the response body but does not connect it to @RestController or content negotiation.

Strong

Explains the serialization mechanism, HttpMessageConverters, content negotiation, and how @RestController combines @Controller with @ResponseBody.

How to structure your answer

  1. Define @ResponseBody and its purpose.
  2. Explain the serialization process through HttpMessageConverters.
  3. Show how @RestController makes it implicit.
  4. Discuss content negotiation and response format.

Key points to hit

  • @ResponseBody tells Spring to serialize the return value of a handler method directly into the HTTP response body instead of resolving a view name.
  • Spring uses HttpMessageConverter implementations to handle serialization, with MappingJackson2HttpMessageConverter for JSON being the default.
  • @RestController is a convenience annotation that combines @Controller and @ResponseBody so you do not need @ResponseBody on every method.
  • The response format is determined by content negotiation based on the Accept header, available message converters, and the produces attribute of @RequestMapping.

Common mistakes

  • Confusing @ResponseBody with @RequestBody when they serve opposite purposes: one writes the response, the other reads the request.
  • Not knowing that @RestController already includes @ResponseBody, leading to redundant annotations on methods.

Sample answer

When you annotate a controller method with @ResponseBody, Spring bypasses the view resolver and writes the return value directly into the HTTP response body. It uses HttpMessageConverters to handle the serialization. If Jackson is on the classpath and the client sends Accept: application/json, Spring uses MappingJackson2HttpMessageConverter to convert your Java object to JSON.

In practice, you rarely use @ResponseBody directly on individual methods because @RestController already includes it. So when I annotate a class with @RestController, every method automatically has @ResponseBody behavior. This is what makes building REST APIs clean in Spring Boot.

If I need one method to return a view and another to return JSON in the same controller, I use @Controller on the class and @ResponseBody only on the JSON methods.

How to level up

  • Mention ResponseEntity as an alternative that gives you control over status codes and headers alongside the body.
  • Discuss how to configure custom HttpMessageConverters for formats like XML, Protocol Buffers, or CSV.
  • Explain content negotiation strategies: Accept header, URL suffix, and request parameter.

Follow-up questions to expect

  • What is the difference between returning an object with @ResponseBody and returning a ResponseEntity?
  • How do you add a custom HttpMessageConverter?
  • How does Spring determine which message converter to use?
Practice this question with AI feedback →
What is the role of @ModelAttribute?
medium

What they're really asking

The interviewer wants to see if you understand Spring MVC's form handling and model population mechanism, which is important for server-side rendered applications.

How you'll be scored

Weak

Has never used @ModelAttribute or confuses it with @RequestBody.

Average

Explains that it binds form data to an object but misses its use on methods for pre-populating model data.

Strong

Explains both uses: parameter binding from form submissions and method-level pre-population of model attributes, with clear examples of each.

How to structure your answer

  1. Explain @ModelAttribute on method parameters for form data binding.
  2. Explain @ModelAttribute on methods for pre-populating model data.
  3. Contrast with @RequestBody for JSON payloads.
  4. Show practical form handling examples.

Key points to hit

  • On a method parameter, @ModelAttribute binds HTTP request parameters (form data, query params) to a Java object by matching field names.
  • On a method, @ModelAttribute runs before every handler method in the controller to add common attributes to the model.
  • It uses setter-based binding, which is different from @RequestBody that uses Jackson deserialization.
  • Supports validation with @Valid, and binding results are captured in a BindingResult parameter.

Common mistakes

  • Using @ModelAttribute for JSON API payloads when @RequestBody is the correct choice for deserialization.
  • Not understanding that @ModelAttribute methods run before every request handler in the controller, which can cause performance issues if they do expensive operations.

Sample answer

@ModelAttribute serves two purposes in Spring MVC. On a method parameter, it binds form data or query parameters to a Java object. For example, when a user submits an HTML form with fields like name and email, Spring automatically creates a User object and populates those fields using setters.

This is different from @RequestBody, which uses Jackson to deserialize JSON. The second use is on a controller method itself. A method annotated with @ModelAttribute runs before every handler method in that controller and adds attributes to the model. I use this to pre-populate dropdown lists or reference data that multiple views need.

For instance, I might have @ModelAttribute("categories") that returns a list of categories available to all form pages in that controller. I pair it with @Valid and BindingResult for server-side form validation.

How to level up

  • Mention that @ModelAttribute is implicitly applied to any method parameter that is not a simple type, so you often do not need the annotation explicitly.
  • Discuss how @ModelAttribute works with Thymeleaf for form rendering and error display.
  • Explain the SessionAttributes annotation for persisting model attributes across multiple requests in a wizard-style form.

Follow-up questions to expect

  • What is the difference between @ModelAttribute and @RequestBody?
  • How do you handle validation errors with @ModelAttribute?
  • Can @ModelAttribute be used with REST controllers?
Practice this question with AI feedback →
How does Spring Boot handle exceptions in REST APIs?
medium

What they're really asking

The interviewer wants to see if you can design clean error handling in REST APIs instead of leaking stack traces or returning inconsistent error formats.

How you'll be scored

Weak

Relies on default Spring Boot error pages without understanding how to customize error responses.

Average

Mentions @ExceptionHandler but does not explain global exception handling or the default error mechanism.

Strong

Explains the default BasicErrorController, @ExceptionHandler, @ControllerAdvice for global handling, and ProblemDetail support for standardized error responses.

How to structure your answer

  1. Explain Spring Boot's default error handling with BasicErrorController.
  2. Show method-level exception handling with @ExceptionHandler.
  3. Explain global exception handling with @ControllerAdvice.
  4. Discuss consistent error response formats.

Key points to hit

  • Spring Boot provides a default /error endpoint through BasicErrorController that returns JSON for API requests and an HTML page for browser requests.
  • @ExceptionHandler on a controller method catches specific exceptions within that controller and lets you return a custom response.
  • @ControllerAdvice combined with @ExceptionHandler creates global exception handlers that apply across all controllers.
  • Spring Boot 3 supports RFC 7807 ProblemDetail for standardized error responses out of the box.

Common mistakes

  • Letting default error responses leak sensitive information like stack traces, package names, or SQL queries to API consumers.
  • Writing exception handling logic in every controller instead of centralizing it in a @ControllerAdvice class.

Sample answer

Spring Boot has a layered approach to REST API exception handling. By default, it provides a /error endpoint through BasicErrorController that returns a JSON error object with status, error, message, and path fields. But for production APIs, I always create a @RestControllerAdvice class that handles specific exceptions globally.

Inside it, I write @ExceptionHandler methods for each exception type. For example, @ExceptionHandler(ResourceNotFoundException.class) returns a ResponseEntity with a 404 status and a consistent error body. For validation failures, I catch MethodArgumentNotValidException and transform the field errors into a clean error response.

In Spring Boot 3, I use the ProblemDetail class which follows RFC 7807 and gives you a standardized error format with type, title, status, detail, and instance fields. This way every error response from my API follows the same structure.

How to level up

  • Mention that @RestControllerAdvice combines @ControllerAdvice with @ResponseBody for cleaner REST exception handling.
  • Discuss how to use ResponseStatusException for quick, inline exception throwing with HTTP status codes.
  • Explain how to customize the default error attributes by extending DefaultErrorAttributes.

Follow-up questions to expect

  • How do you prevent stack traces from appearing in production error responses?
  • What is RFC 7807 ProblemDetail and how does Spring Boot 3 support it?
  • How do you handle validation errors in a consistent way across all endpoints?
Practice this question with AI feedback →
What is @ControllerAdvice and @ExceptionHandler?
medium

What they're really asking

The interviewer wants to see if you can implement centralized, clean exception handling across your entire Spring application rather than duplicating try-catch logic in every controller.

How you'll be scored

Weak

Vaguely knows they are related to error handling but cannot explain how they work together.

Average

Correctly explains both annotations but does not discuss scoping, ordering, or response customization.

Strong

Explains the combination for global exception handling, shows how to scope advice to specific controllers, and demonstrates building consistent error responses.

How to structure your answer

  1. Define @ControllerAdvice as a class-level annotation for cross-cutting controller concerns.
  2. Define @ExceptionHandler as a method-level annotation that catches specific exceptions.
  3. Show how they combine for global exception handling.
  4. Discuss scoping and ordering of multiple advice classes.

Key points to hit

  • @ControllerAdvice is a specialization of @Component that applies cross-cutting concerns to all controllers, including exception handling, model attributes, and data binding.
  • @ExceptionHandler on a method specifies which exception types it handles and lets you return a custom response with any status code.
  • Together, @ControllerAdvice with @ExceptionHandler methods creates a centralized error handling layer that catches exceptions from any controller.
  • @ControllerAdvice can be scoped to specific packages, annotations, or base classes using its attributes.

Common mistakes

  • Creating multiple @ControllerAdvice classes that handle the same exception type without @Order, leading to unpredictable behavior.
  • Using @ControllerAdvice only for exceptions when it can also handle @ModelAttribute and @InitBinder globally.

Sample answer

@ControllerAdvice is a specialized @Component that intercepts cross-cutting concerns across all controllers. @ExceptionHandler is a method annotation that specifies which exception types the method handles. Together, they create centralized exception handling. I create a class annotated with @RestControllerAdvice and add methods like @ExceptionHandler(EntityNotFoundException.class) that return a ResponseEntity with the right status code and error body.

The key benefit is that I write this once, and it handles that exception type no matter which controller throws it. I can scope my advice to specific packages using @ControllerAdvice(basePackages = "com.myapp.api.v1") if I need different error formats for different API versions.

When I have multiple advice classes, I use @Order to control which one gets priority for overlapping exception types.

How to level up

  • Mention that @ControllerAdvice also supports @InitBinder for global data binding customization and @ModelAttribute for global model attributes.
  • Discuss the difference between @ControllerAdvice and @RestControllerAdvice, which adds @ResponseBody implicitly.
  • Explain exception handling order: method-level @ExceptionHandler in the controller takes precedence over @ControllerAdvice handlers.

Follow-up questions to expect

  • How do you handle different exception types with different HTTP status codes in a single @ControllerAdvice?
  • What happens if two @ControllerAdvice classes handle the same exception type?
  • Can @ControllerAdvice catch exceptions thrown by filters?
Practice this question with AI feedback →
What is Thymeleaf and how is it used in Spring Boot?
medium

What they're really asking

This tests whether you understand server-side templating in Spring Boot's web stack and can articulate when template engines like Thymeleaf are appropriate versus client-side frameworks.

How you'll be scored

Weak

Vague description of Thymeleaf as 'a template engine' without understanding its role in Spring Boot's MVC architecture.

Average

Correctly identifies Thymeleaf as a server-side template engine with basic syntax knowledge but no architectural context.

Strong

Demonstrates understanding of Thymeleaf's natural templating approach, Spring Boot auto-configuration, and when to choose it over alternatives.

How to structure your answer

  1. Define Thymeleaf as a server-side template engine.
  2. Explain its natural templating philosophy.
  3. Show how Spring Boot auto-configures it.
  4. Provide concrete syntax examples.
  5. Discuss when to use versus alternatives.

Key points to hit

  • Thymeleaf is a server-side Java template engine that creates HTML, XML, and other markup.
  • Spring Boot auto-configures Thymeleaf when it's on the classpath with spring-boot-starter-thymeleaf.
  • Natural templating means templates are valid HTML that can be opened in browsers.
  • Integrates seamlessly with Spring MVC for form binding and validation display.

Common mistakes

  • Confusing Thymeleaf with client-side frameworks like React or Angular.
  • Not understanding that Thymeleaf renders on the server, not in the browser.

Sample answer

Thymeleaf is a server-side template engine that Spring Boot auto-configures when you include the spring-boot-starter-thymeleaf dependency. What makes it unique is natural templating, meaning your templates are valid HTML files that designers can open directly in browsers. For example, th:text='${user.name}' replaces the element content with the user's name from your model.

Spring Boot automatically sets up the TemplateResolver and ViewResolver, so you just return view names from your @Controller methods. It's great for traditional web applications where you want server-side rendering, but for APIs or SPAs, you'd skip it entirely.

How to level up

  • Mention Thymeleaf's fragment system for reusable components and layouts.
  • Discuss performance implications of server-side rendering versus client-side alternatives.
  • Show knowledge of Thymeleaf's Spring Security integration for conditional rendering.

Follow-up questions to expect

  • How would you handle internationalization with Thymeleaf in Spring Boot?
  • What's the difference between th:text and th:utext?
  • When would you choose Thymeleaf over a REST API with a JavaScript frontend?
Practice this question with AI feedback →
What is Spring Data REST?
medium

What they're really asking

This tests your understanding of Spring's convention-over-configuration approach to automatically expose JPA repositories as REST endpoints and whether you recognize its limitations.

How you'll be scored

Weak

Confused about what Spring Data REST does or thinks it's the same as regular Spring Data JPA.

Average

Knows it auto-exposes repositories as REST endpoints but doesn't understand the HATEOAS principles or configuration options.

Strong

Understands the automatic REST endpoint generation, HATEOAS compliance, and can explain why it's often unsuitable for production.

How to structure your answer

  1. Define Spring Data REST as automatic REST API generation.
  2. Explain how it works with repositories.
  3. Describe HATEOAS compliance.
  4. Show configuration examples.
  5. Discuss practical limitations.

Key points to hit

  • Spring Data REST automatically exposes Spring Data repositories as REST endpoints.
  • Follows HATEOAS principles with hypermedia links in responses.
  • Uses spring-boot-starter-data-rest and works with @RepositoryRestResource annotation.
  • Provides automatic CRUD operations, pagination, and sorting without writing controllers.

Common mistakes

  • Thinking Spring Data REST is suitable for complex business logic.
  • Not understanding that it directly exposes your data model without transformation.

Sample answer

Spring Data REST automatically turns your Spring Data repositories into REST endpoints without writing any controller code. When you add spring-boot-starter-data-rest, it scans for repositories and creates endpoints like GET /users, POST /users, etc. The responses follow HATEOAS principles, including navigation links.

For example, a User repository becomes a /users endpoint with full CRUD operations, pagination, and sorting built-in. You can customize it with @RepositoryRestResource annotations, but the main issue is it directly exposes your domain model, which rarely matches what your API clients actually need.

How to level up

  • Explain how to use projections and excerpts to control data exposure.
  • Discuss event handlers for adding business logic to Spring Data REST operations.
  • Mention security implications of auto-exposing repository methods.

Follow-up questions to expect

  • How would you add validation to Spring Data REST endpoints?
  • What are projections in Spring Data REST?
  • How does Spring Data REST handle relationships between entities?
Practice this question with AI feedback →
Why is Spring Data REST not recommended in real-world production applications?
medium

What they're really asking

This tests whether you understand the gap between rapid prototyping tools and production-ready APIs, specifically around business logic, security, and API design principles.

How you'll be scored

Weak

Cannot articulate specific problems with Spring Data REST or thinks it's always appropriate.

Average

Mentions that it exposes too much but doesn't explain the business logic, security, or API design issues.

Strong

Clearly explains multiple production concerns: business logic bypass, security exposure, tight coupling, and lack of API design control.

How to structure your answer

  1. Acknowledge Spring Data REST's prototyping value.
  2. Explain business logic bypass problems.
  3. Discuss security and data exposure risks.
  4. Address API design and client coupling issues.
  5. Recommend when to use traditional controllers instead.

Key points to hit

  • Bypasses business logic layer, allowing direct data manipulation without validation or business rules.
  • Exposes internal domain model structure, creating tight coupling with clients.
  • Security risks from automatic endpoint exposure without proper access control.
  • Limited control over API design, making it hard to evolve or optimize for client needs.

Common mistakes

  • Thinking Spring Data REST can be easily secured or customized for complex business needs.
  • Not understanding that good APIs should hide implementation details from clients.

Sample answer

Spring Data REST bypasses your service layer completely, which means business logic, validation, and security rules get skipped. Clients directly manipulate your database through the repository, which is dangerous. It also exposes your internal domain model structure, so any database changes break your API clients.

You can't easily add authentication, authorization, or audit logging because there's no controller layer to intercept requests. Plus, the HATEOAS responses are often too verbose for mobile clients or single-page applications that need optimized payloads. It's great for prototypes, but production APIs need proper service layers and designed endpoints.

How to level up

  • Explain how Spring Data REST makes API versioning nearly impossible.
  • Discuss performance implications of exposing lazy-loaded relationships.
  • Mention compliance issues when audit trails or data transformation are required.

Follow-up questions to expect

  • How would you migrate from Spring Data REST to traditional controllers?
  • What architectural patterns do you prefer for REST API design?
  • How do you handle API versioning in Spring Boot applications?
Practice this question with AI feedback →
What are Spring Interceptors and how do they work?
medium

What they're really asking

This tests your understanding of Spring MVC's request processing pipeline and whether you can implement cross-cutting concerns at the right architectural level.

How you'll be scored

Weak

Confuses interceptors with filters or doesn't understand where they fit in the request lifecycle.

Average

Knows interceptors run before/after controller methods but can't explain the HandlerInterceptor interface or configuration.

Strong

Understands the three interceptor methods, execution order, and can compare interceptors to filters and AOP for different use cases.

How to structure your answer

  1. Define interceptors in Spring MVC request processing.
  2. Explain HandlerInterceptor interface methods.
  3. Show configuration with WebMvcConfigurer.
  4. Demonstrate common use cases.
  5. Compare with filters and AOP alternatives.

Key points to hit

  • Interceptors run after servlet filters but before controller methods in Spring MVC.
  • HandlerInterceptor has preHandle, postHandle, and afterCompletion methods.
  • Configured by implementing WebMvcConfigurer and overriding addInterceptors.
  • Perfect for authentication, logging, request preprocessing that needs Spring context.

Common mistakes

  • Confusing interceptors with servlet filters in terms of execution order and capabilities.
  • Not understanding that interceptors have access to the handler method and ModelAndView.

Sample answer

Spring interceptors implement cross-cutting concerns in the MVC request pipeline, running after servlet filters but before your controller methods. They implement HandlerInterceptor with three methods: preHandle runs before the controller, postHandle runs after but before view rendering, and afterCompletion runs after everything. You configure them by implementing WebMvcConfigurer and overriding addInterceptors.

I've used them for request logging, authentication checks, and adding common model attributes. Unlike filters, interceptors have full access to Spring context and can see which controller method will handle the request, making them perfect for Spring-specific concerns.

How to level up

  • Explain how to use HandlerMethod parameter to get controller method metadata.
  • Discuss interceptor ordering when multiple interceptors are registered.
  • Show how interceptors can modify ModelAndView in postHandle method.

Follow-up questions to expect

  • What's the difference between interceptors and servlet filters?
  • How would you implement request rate limiting using interceptors?
  • When would you choose AOP over interceptors for cross-cutting concerns?
Practice this question with AI feedback →
How is form data validation done in Spring MVC?
medium

What they're really asking

This tests whether you understand Spring MVC's validation framework integration and can implement both client-side and server-side validation with proper error handling.

How you'll be scored

Weak

Only mentions basic validation without understanding Bean Validation annotations or error handling.

Average

Knows about @Valid and basic validation annotations but can't explain error binding or display.

Strong

Demonstrates understanding of Bean Validation, BindingResult, custom validators, and error display in views.

How to structure your answer

  1. Explain Bean Validation integration with Spring MVC.
  2. Show validation annotations on form objects.
  3. Demonstrate controller method with @Valid and BindingResult.
  4. Explain error display in views.
  5. Discuss custom validation scenarios.

Key points to hit

  • Spring MVC integrates with Bean Validation using @Valid annotation in controller methods.
  • BindingResult captures validation errors and must immediately follow the validated parameter.
  • Validation annotations like @NotNull, @Size, @Email on form backing objects.
  • Thymeleaf or JSP can display field errors using Spring's error message system.

Common mistakes

  • Forgetting that BindingResult must be the parameter immediately after the @Valid object.
  • Not understanding the difference between binding errors and validation errors.

Sample answer

Form validation in Spring MVC uses Bean Validation annotations like @NotNull and @Size on your form backing objects. In the controller, you annotate the parameter with @Valid and include a BindingResult parameter immediately after it. If validation fails, errors populate the BindingResult instead of throwing exceptions.

You check bindingResult.hasErrors() and return to the form view if there are problems. In Thymeleaf, you display errors using th:errors='*{fieldName}'. I've also implemented custom validators by creating @Constraint annotations with ConstraintValidator implementations for business-specific rules like unique email validation.

How to level up

  • Explain validation groups for different validation scenarios on the same object.
  • Show how to create custom validation messages with MessageSource.
  • Discuss @InitBinder for custom data binding and validation configuration.

Follow-up questions to expect

  • How do you handle validation in REST controllers versus form controllers?
  • What's the difference between @Valid and @Validated?
  • How would you implement cross-field validation like password confirmation?
Practice this question with AI feedback →
What is content negotiation in Spring MVC?
medium

What they're really asking

The interviewer wants to see if you understand how Spring MVC serves different response formats based on client preferences and can configure content negotiation for multi-format APIs.

How you'll be scored

Weak

Does not know what content negotiation is or assumes all responses are always JSON.

Average

Explains the Accept header mechanism but does not know about other strategies or how to configure them.

Strong

Explains all content negotiation strategies, how HttpMessageConverters tie in, and how to configure it for APIs that need to support multiple formats.

How to structure your answer

  1. Define content negotiation as the mechanism for determining response format.
  2. Explain the Accept header strategy.
  3. Discuss other strategies like URL suffix and query parameter.
  4. Show how HttpMessageConverters handle the actual serialization.

Key points to hit

  • Content negotiation determines the response format (JSON, XML, etc.) based on what the client requests and what the server can produce.
  • The primary strategy uses the HTTP Accept header, where the client sends Accept: application/json or Accept: application/xml.
  • Spring Boot auto-configures Jackson for JSON, and adding jackson-dataformat-xml enables XML support alongside JSON.
  • The produces attribute on @RequestMapping can restrict which formats an endpoint supports.

Common mistakes

  • Assuming Spring Boot only supports JSON when adding a single dependency can enable XML, CSV, or other formats.
  • Not knowing how to restrict an endpoint to specific media types using the produces attribute.

Sample answer

Content negotiation is how Spring MVC decides what format to use for the response body. When a client sends a request with Accept: application/json, Spring uses MappingJackson2HttpMessageConverter to serialize the response as JSON. If the client sends Accept: application/xml and I have the jackson-dataformat-xml dependency on the classpath, Spring automatically uses the XML converter instead.

The beauty is that the same controller method serves both formats without any code changes. I can restrict what an endpoint produces using @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE) if I want to limit it to JSON only. Spring Boot also supports content negotiation through query parameters with spring.mvc.contentnegotiation.favor-parameter=true, so a client could use /api/users?format=xml.

In my experience, most modern APIs only need JSON, but content negotiation becomes essential when supporting legacy clients or B2B integrations that require XML.

How to level up

  • Mention how to create custom HttpMessageConverters for specialized formats like CSV or Protocol Buffers.
  • Discuss configuring ContentNegotiationConfigurer in a WebMvcConfigurer for fine-grained control.
  • Explain that path extension strategy (e.g., /users.json) was deprecated in Spring 5.3 due to security concerns with RFD attacks.

Follow-up questions to expect

  • How do you add XML support to a Spring Boot REST API?
  • What happens when the client requests a format the server does not support?
  • How do you create a custom HttpMessageConverter?
Practice this question with AI feedback →

Ready to put this into practice?

Try these questions in a mock interview →

Still applying for jobs? Let Auto Apply do it

Spring MVC & REST APIs (Advanced) (7)

How do you version REST APIs in Spring Boot?
hard

What they're really asking

The interviewer wants to see if you have dealt with API evolution in production and can design a versioning strategy that supports backward compatibility without breaking existing clients.

How you'll be scored

Weak

Does not know any versioning strategies or thinks you just change the endpoints and hope clients adapt.

Average

Lists URL path versioning as the only approach without discussing trade-offs or alternatives.

Strong

Explains multiple strategies, their trade-offs, and shows experience implementing versioning in Spring Boot with specific annotations and configuration.

How to structure your answer

  1. List the main versioning strategies.
  2. Explain implementation in Spring Boot for each.
  3. Discuss trade-offs and when to use each approach.
  4. Recommend a pragmatic default.

Key points to hit

  • URL path versioning (/api/v1/users, /api/v2/users) is the most common and simplest to implement with separate controllers or @RequestMapping base paths.
  • Request header versioning uses a custom header like X-API-Version and maps using the headers attribute of @RequestMapping.
  • Content type versioning uses Accept: application/vnd.myapp.v2+json and maps using the produces attribute.
  • Query parameter versioning (/api/users?version=2) uses @RequestParam but is less RESTful.

Common mistakes

  • Choosing a versioning strategy without considering your API consumers, such as using header versioning for a public API where URL versioning is more discoverable.
  • Creating a new version for every minor change instead of making backward-compatible additions to the existing version.

Sample answer

There are four main strategies for API versioning in Spring Boot. URL path versioning is the most popular and what I default to. I create separate controller packages for each version, with @RequestMapping("/api/v1") and @RequestMapping("/api/v2") as base paths. Header versioning uses a custom header like X-API-Version, and I map it with @GetMapping(headers = "X-API-Version=2").

Content type versioning uses custom media types in the Accept header, mapped with @GetMapping(produces = "application/vnd.myapp.v2+json"). I prefer URL path versioning for public APIs because it is visible, cacheable, and easy for clients to understand. For internal microservice APIs where I control both sides, header versioning works well because URLs stay clean.

The most important thing is to version sparingly. I only create a new version for breaking changes and make non-breaking additions to the existing version.

How to level up

  • Discuss API deprecation strategies using custom response headers like Deprecation and Sunset to warn clients of upcoming version retirement.
  • Mention using Spring HATEOAS links to guide clients to the latest API version.
  • Explain how to share common logic between versions using service layer abstractions and versioned DTOs.

Follow-up questions to expect

  • How do you deprecate and retire an old API version safely?
  • How do you handle clients that do not specify a version?
  • What constitutes a breaking change that requires a new API version?
Practice this question with AI feedback →
How do you handle CORS (Cross-Origin Resource Sharing) in Spring Boot?
hard

What they're really asking

The interviewer wants to see if you understand browser security policies and can configure CORS correctly for frontend-backend communication without introducing security vulnerabilities.

How you'll be scored

Weak

Does not understand why CORS exists or suggests disabling it entirely as the fix.

Average

Knows about @CrossOrigin but does not understand global configuration or the security implications of overly permissive settings.

Strong

Explains the CORS mechanism, demonstrates multiple configuration approaches, and discusses security considerations for production settings.

How to structure your answer

  1. Explain why CORS exists and the same-origin policy.
  2. Show controller-level configuration with @CrossOrigin.
  3. Show global configuration with WebMvcConfigurer.
  4. Discuss security considerations and Spring Security integration.

Key points to hit

  • @CrossOrigin on a controller or method enables CORS for specific endpoints with configurable origins, methods, and headers.
  • Global CORS configuration through WebMvcConfigurer.addCorsMappings() applies to all endpoints matching a pattern.
  • When Spring Security is active, CORS must also be enabled in the security filter chain with http.cors() to avoid preflight requests being blocked.
  • Never use allowedOrigins("*") with allowCredentials(true) in production because it exposes authenticated endpoints to any domain.

Common mistakes

  • Setting allowedOrigins to * in production, which allows any website to make requests to your API.
  • Forgetting to configure CORS in Spring Security when it is active, which causes preflight OPTIONS requests to get 401 responses.

Sample answer

CORS is the browser mechanism that controls which domains can make requests to your API. In Spring Boot, I handle it at three levels. For individual endpoints, I use @CrossOrigin(origins = "https://myapp.com") on a controller or method.

For global configuration, I implement WebMvcConfigurer and override addCorsMappings to set allowed origins, methods, headers, and max age for all endpoints matching a path pattern. When Spring Security is in the picture, I also call http.cors(Customizer.withDefaults()) in my SecurityFilterChain, which delegates to the CORS configuration I already defined.

This is critical because otherwise Spring Security's filter chain blocks preflight OPTIONS requests before they reach the CORS handler. In production, I always specify exact allowed origins instead of using wildcards, and I limit allowed methods to only what the frontend actually needs.

How to level up

  • Discuss how to configure CORS with a CorsConfigurationSource bean for dynamic origin resolution based on database or configuration lookups.
  • Mention that preflight requests cache according to the Access-Control-Max-Age header, reducing the number of OPTIONS requests.
  • Explain the difference between simple requests that skip preflight and preflighted requests that trigger an OPTIONS check.

Follow-up questions to expect

  • What is a preflight request and when does the browser send one?
  • How does CORS interact with Spring Security's filter chain?
  • What are the security risks of overly permissive CORS settings?
Practice this question with AI feedback →
What is HATEOAS and how do you implement it?
hard

What they're really asking

The interviewer wants to see if you understand REST maturity beyond basic CRUD endpoints and can implement hypermedia-driven APIs that guide clients through available actions.

How you'll be scored

Weak

Has never heard of HATEOAS or confuses it with basic REST APIs.

Average

Knows HATEOAS stands for Hypermedia as the Engine of Application State but cannot explain the implementation in Spring.

Strong

Explains the concept, demonstrates Spring HATEOAS implementation with EntityModel, Link, and RepresentationModelAssembler, and articulates the benefits for API evolution.

How to structure your answer

  1. Define HATEOAS and the Richardson Maturity Model context.
  2. Explain how hypermedia links guide API navigation.
  3. Show Spring HATEOAS implementation details.
  4. Discuss practical benefits and when to use it.

Key points to hit

  • HATEOAS is the highest level of REST maturity where API responses include hypermedia links that tell clients what actions are available and how to navigate the API.
  • Spring HATEOAS provides EntityModel to wrap resources with links, CollectionModel for lists, and WebMvcLinkBuilder for generating type-safe links.
  • RepresentationModelAssembler converts domain objects to link-enriched representations in a reusable way.
  • Benefits include API discoverability, decoupling clients from hardcoded URLs, and easier API evolution since clients follow links rather than constructing URLs.

Common mistakes

  • Thinking HATEOAS is required for every REST API when it adds complexity that only pays off for APIs with complex navigation and many consumers.
  • Manually building link URLs as strings instead of using WebMvcLinkBuilder which generates them from controller method signatures.

Sample answer

HATEOAS stands for Hypermedia as the Engine of Application State. It means API responses include links that tell clients what they can do next. Instead of a client hardcoding "/api/orders/42/cancel", the order response includes a "cancel" link that the client follows. I implement this in Spring Boot using the spring-boot-starter-hateoas dependency.

I wrap my domain objects in EntityModel and add links using WebMvcLinkBuilder.linkTo(). For example, EntityModel.of(user, linkTo(methodOn(UserController.class).getUser(user.getId())).withSelfRel()) generates a self link. For collections, I use CollectionModel. I also create RepresentationModelAssembler implementations that encapsulate the link-building logic so controllers stay clean. The real benefit is API evolution.

When I add a new action or change a URL structure, clients that follow links adapt automatically without code changes.

How to level up

  • Discuss HAL (Hypertext Application Language) as the default media type in Spring HATEOAS with _links and _embedded sections.
  • Mention affordances that describe not just where to navigate but what methods and input are expected.
  • Explain how HATEOAS enables conditional links where certain actions only appear based on resource state, like showing a "cancel" link only for pending orders.

Follow-up questions to expect

  • What is the Richardson Maturity Model?
  • When is HATEOAS overkill for a REST API?
  • How do you handle pagination links with Spring HATEOAS?
Practice this question with AI feedback →
What is the difference between synchronous and asynchronous request handling in Spring MVC?
hard

What they're really asking

The interviewer wants to see if you understand thread management in web applications and can use async processing to improve throughput for I/O-bound operations.

How you'll be scored

Weak

Does not understand threading in Spring MVC or confuses async with parallel processing.

Average

Explains that async frees up the request thread but cannot detail the implementation mechanisms.

Strong

Explains the thread model difference, demonstrates multiple async approaches (DeferredResult, Callable, CompletableFuture, @Async), and knows when async actually helps.

How to structure your answer

  1. Explain the synchronous thread model and its limitations.
  2. Explain how async releases the servlet thread while work continues.
  3. List the async mechanisms available in Spring MVC.
  4. Discuss when async actually improves performance.

Key points to hit

  • Synchronous handling blocks the servlet container thread for the entire request lifecycle, limiting concurrent request capacity to the thread pool size.
  • Async handling releases the servlet thread after accepting the request, processes work on a separate thread, and completes the response when ready.
  • Spring MVC supports async via Callable return types, DeferredResult for event-driven completion, CompletableFuture, and @Async annotated service methods.
  • Async improves throughput for I/O-bound operations like external API calls and database queries, but does not help CPU-bound work.

Common mistakes

  • Thinking async makes individual requests faster when it actually improves server throughput by handling more concurrent requests with fewer threads.
  • Using async for CPU-bound operations where it just moves the work to a different thread pool without any throughput benefit.

Sample answer

In synchronous Spring MVC, each request occupies a servlet container thread from start to finish. If you have a 200-thread pool and 200 requests are waiting on slow database calls, your server cannot accept new requests. Async handling changes this by releasing the servlet thread while long-running work happens on a different thread.

I return a Callable<ResponseEntity> from my controller method, and Spring runs it on a task executor while freeing the Tomcat thread. For more control, I return DeferredResult, which lets me complete the response from any thread, like a message listener or callback.

I also use @Async on service methods combined with CompletableFuture to parallelize multiple external API calls. The key insight is that async improves throughput, not latency. A single request does not get faster. But the server can handle many more concurrent requests because servlet threads are not sitting idle waiting for I/O.

How to level up

  • Mention configuring a custom AsyncTaskExecutor to control thread pool sizing for async processing.
  • Discuss how Spring WebFlux takes async further with a fully non-blocking, event-loop model instead of thread-per-request.
  • Explain Server-Sent Events (SSE) using SseEmitter for streaming async responses to clients.

Follow-up questions to expect

  • What is the difference between DeferredResult and Callable in Spring MVC?
  • How do you configure the thread pool for async request processing?
  • When would you choose Spring WebFlux over async Spring MVC?
Practice this question with AI feedback →
What is Spring WebFlux and how does it differ from Spring MVC?
hard

What they're really asking

This tests your understanding of reactive programming paradigms and whether you can differentiate between traditional blocking I/O patterns in Spring MVC versus non-blocking reactive streams in WebFlux.

How you'll be scored

Weak

Cannot explain the blocking versus non-blocking difference or thinks WebFlux is just a newer version of Spring MVC.

Average

Correctly identifies WebFlux as reactive and mentions non-blocking I/O but lacks depth on when to choose each approach.

Strong

Demonstrates understanding of reactive streams, backpressure, and can articulate specific use cases where WebFlux's non-blocking nature provides advantages over Spring MVC's thread-per-request model.

How to structure your answer

  1. Define WebFlux as Spring's reactive web framework.
  2. Contrast threading models: thread-per-request vs event loop.
  3. Explain when WebFlux provides benefits.
  4. Discuss trade-offs and complexity considerations.
  5. Mention production implications for scalability.

Key points to hit

  • Spring WebFlux uses reactive streams with non-blocking I/O while Spring MVC uses blocking thread-per-request model.
  • WebFlux excels with high-concurrency, I/O-intensive applications but adds complexity.
  • Both can run on Netty, but WebFlux can handle thousands of concurrent connections with fewer threads.
  • WebFlux requires reactive database drivers and different debugging approaches.

Common mistakes

  • Thinking WebFlux automatically makes any application faster without considering the I/O bound nature requirement.
  • Not understanding that WebFlux requires end-to-end reactive stack to realize benefits.

Sample answer

Spring WebFlux is Spring's reactive web framework built on Project Reactor, designed for non-blocking I/O operations. Unlike Spring MVC which uses a thread-per-request model where each request blocks a thread until completion, WebFlux uses an event-loop model that can handle thousands of concurrent connections with just a few threads.

WebFlux shines in I/O-intensive applications like API gateways or services making many external calls, but it adds complexity with its functional programming style and requires reactive database drivers. For traditional CRUD applications with blocking database operations, Spring MVC is often the better choice due to its simplicity and mature ecosystem.

How to level up

  • Discuss Project Reactor's Mono and Flux types and their role in reactive streams.
  • Mention that WebFlux supports both annotation-based and functional routing approaches.
  • Explain how backpressure handling works in reactive streams to prevent overwhelming downstream services.

Follow-up questions to expect

  • Can you explain what Mono and Flux are in Project Reactor?
  • When would you choose WebFlux over Spring MVC for a real project?
  • How do you handle error scenarios in reactive streams?
Practice this question with AI feedback →
What is Reactive Programming in Spring?
hard

What they're really asking

This tests your grasp of reactive programming fundamentals and whether you understand how Spring implements reactive patterns through Project Reactor and reactive streams.

How you'll be scored

Weak

Provides vague definition about being 'faster' or 'asynchronous' without understanding reactive streams or backpressure concepts.

Average

Correctly mentions non-blocking operations and reactive streams but cannot explain practical implementation details or benefits.

Strong

Demonstrates deep understanding of reactive streams specification, Project Reactor types, and can explain how backpressure and operators work in practice.

How to structure your answer

  1. Define reactive programming principles.
  2. Explain Project Reactor as Spring's reactive implementation.
  3. Describe Mono and Flux reactive types.
  4. Discuss operators and composition patterns.
  5. Address backpressure and error handling.

Key points to hit

  • Reactive programming handles asynchronous data streams with non-blocking operations and functional composition.
  • Spring uses Project Reactor implementing Reactive Streams specification with Publisher-Subscriber pattern.
  • Mono represents 0-1 elements while Flux represents 0-N elements in reactive streams.
  • Operators like map, filter, and flatMap allow declarative stream processing with automatic backpressure management.

Common mistakes

  • Confusing reactive programming with just async programming or multithreading.
  • Not understanding that reactive benefits require non-blocking I/O throughout the entire stack.

Sample answer

Reactive programming in Spring is based on handling asynchronous data streams using non-blocking I/O operations. Spring implements this through Project Reactor, which follows the Reactive Streams specification with Publisher-Subscriber patterns. The core types are Mono for 0-1 elements and Flux for 0-N elements, both supporting functional operators like map, filter, and flatMap for stream transformation.

The key advantage is handling backpressure automatically when producers generate data faster than consumers can process, and the declarative style makes complex asynchronous operations more readable than traditional callback-based approaches.

How to level up

  • Explain how schedulers work in Project Reactor for controlling execution context.
  • Discuss cold vs hot publishers and their implications for stream behavior.
  • Mention how reactive programming integrates with Spring Security and database access layers.

Follow-up questions to expect

  • How do you handle errors in reactive streams?
  • What's the difference between cold and hot publishers?
  • How would you test reactive code in Spring?
Practice this question with AI feedback →
What is the difference between WebClient and RestTemplate?
hard

What they're really asking

This tests whether you understand the evolution from blocking RestTemplate to non-blocking WebClient and can choose the appropriate HTTP client based on application requirements.

How you'll be scored

Weak

Cannot explain the blocking versus non-blocking difference or doesn't know that RestTemplate is deprecated in favor of WebClient.

Average

Knows WebClient is newer and non-blocking but cannot articulate specific advantages or when to use each approach.

Strong

Clearly explains threading models, performance implications, and demonstrates understanding of reactive vs imperative programming styles for HTTP clients.

How to structure your answer

  1. Contrast blocking vs non-blocking I/O models.
  2. Explain RestTemplate's synchronous thread-per-request approach.
  3. Describe WebClient's reactive non-blocking design.
  4. Compare performance characteristics and use cases.
  5. Mention deprecation status and migration considerations.

Key points to hit

  • RestTemplate blocks threads during HTTP calls while WebClient uses non-blocking I/O with reactive streams.
  • WebClient supports both reactive and blocking programming styles through block() method.
  • RestTemplate is in maintenance mode since Spring 5.0 with WebClient as the recommended replacement.
  • WebClient provides better resource utilization for applications making many concurrent HTTP calls.

Common mistakes

  • Using RestTemplate in new projects without considering WebClient's advantages.
  • Not understanding that WebClient's benefits require non-blocking usage patterns to be effective.

Sample answer

RestTemplate is Spring's traditional synchronous HTTP client that blocks the calling thread until the response returns, following a thread-per-request model. WebClient is the modern reactive HTTP client introduced in Spring 5.0 that uses non-blocking I/O and returns Mono or Flux types for reactive stream processing.

While RestTemplate is simpler for basic HTTP calls, WebClient provides better resource utilization when making many concurrent requests because it doesn't tie up threads waiting for responses. RestTemplate is now in maintenance mode, so WebClient is recommended for new development, though you can still use WebClient synchronously with the block() method if needed.

How to level up

  • Discuss WebClient's fluent API design and how it simplifies request building and response handling.
  • Explain connection pooling differences and how WebClient can be configured with custom connection managers.
  • Mention WebClient's superior testing support through WebTestClient for integration testing.

Follow-up questions to expect

  • How would you configure connection pooling with WebClient?
  • Can you show how to handle errors differently in RestTemplate versus WebClient?
  • How do you test HTTP clients in Spring Boot applications?
Practice this question with AI feedback →

Spring Data JPA (Beginner) (4)

What is Spring Data JPA?
easy

What they're really asking

This tests your understanding of Spring Boot's data access layer abstraction and whether you know how it simplifies database operations through convention over configuration.

How you'll be scored

Weak

Provides vague answer about database access without mentioning JPA, repository pattern, or Spring Boot's auto-configuration benefits.

Average

Correctly identifies it as database abstraction layer but cannot explain specific features like query derivation or auto-configuration.

Strong

Demonstrates understanding of JPA abstraction, repository pattern, query derivation, and Spring Boot's auto-configuration for datasources and entity management.

How to structure your answer

  1. Define Spring Data JPA as abstraction over JPA.
  2. Explain repository pattern implementation.
  3. Describe auto-configuration benefits.
  4. Mention query derivation and custom queries.
  5. Discuss integration with Spring Boot features.

Key points to hit

  • Spring Data JPA provides repository abstraction layer on top of JPA implementations like Hibernate.
  • Eliminates boilerplate code through automatic CRUD operations and query derivation from method names.
  • Spring Boot auto-configures datasource, entity manager, and transaction management.
  • Supports both derived queries and custom @Query annotations for complex operations.

Common mistakes

  • Thinking Spring Data JPA is a JPA implementation rather than an abstraction layer.
  • Not understanding that it still requires a JPA provider like Hibernate underneath.

Sample answer

Spring Data JPA is Spring's abstraction layer built on top of JPA that dramatically reduces boilerplate code for database operations. It provides the repository pattern where you define interfaces extending JpaRepository, and Spring automatically generates implementations with standard CRUD operations.

The framework can derive queries from method names like findByFirstNameAndLastName, or you can use @Query annotations for complex operations. Spring Boot auto-configures the datasource, entity manager factory, and transaction manager based on dependencies and properties, so you can focus on business logic rather than infrastructure setup.

How to level up

  • Explain how Spring Data JPA integrates with Spring Boot Actuator for database health checks and metrics.
  • Discuss pagination and sorting capabilities through PagingAndSortingRepository.
  • Mention custom repository implementations for complex business logic that doesn't fit the standard repository pattern.

Follow-up questions to expect

  • How do you handle transactions in Spring Data JPA?
  • What's the difference between save() and saveAndFlush() methods?
  • How would you implement custom repository methods that aren't auto-generated?
Practice this question with AI feedback →
What is a JPA Repository?
easy

What they're really asking

This tests whether you understand the repository pattern implementation in Spring Data JPA and can explain the interface hierarchy that provides different levels of functionality.

How you'll be scored

Weak

Cannot explain what repositories provide beyond basic database access or doesn't understand the interface hierarchy.

Average

Knows repositories provide CRUD operations but cannot differentiate between Repository, CrudRepository, and JpaRepository interfaces.

Strong

Clearly explains the repository interface hierarchy, different capability levels, and when to extend each interface based on application needs.

How to structure your answer

  1. Define repository pattern in Spring Data context.
  2. Explain the interface hierarchy from Repository to JpaRepository.
  3. Describe capabilities at each level.
  4. Show method naming conventions for query derivation.
  5. Discuss when to use each repository type.

Key points to hit

  • JPA Repository is an interface-based abstraction following repository pattern for data access layer.
  • Interface hierarchy: Repository (marker) -> CrudRepository (basic CRUD) -> PagingAndSortingRepository (pagination) -> JpaRepository (JPA-specific)
  • Spring generates proxy implementations at runtime with automatic CRUD operations and query derivation.
  • Method names like findBy, deleteBy, and countBy are automatically translated to appropriate JPA queries.

Common mistakes

  • Extending JpaRepository when you only need basic CRUD operations, adding unnecessary dependencies.
  • Not understanding that repositories are interfaces and Spring provides runtime implementations.

Sample answer

A JPA Repository is an interface in Spring Data JPA that follows the repository pattern to encapsulate data access logic. You typically extend JpaRepository<Entity, ID> which provides a complete set of CRUD operations, batch operations, and JPA-specific methods like flush() and saveAndFlush().

The framework automatically generates implementations at runtime, so you just declare method signatures like findByEmail(String email) and Spring derives the appropriate JPA query. There's a hierarchy where CrudRepository provides basic operations, PagingAndSortingRepository adds pagination support, and JpaRepository includes JPA-specific batch operations.

How to level up

  • Explain how to create custom repository interfaces when you only need specific operations without inheriting unnecessary methods.
  • Discuss @Modifying annotation for update and delete queries with custom @Query methods.
  • Mention repository metrics and how Spring Boot Actuator can monitor repository performance.

Follow-up questions to expect

  • How do you write custom queries that can't be derived from method names?
  • What's the difference between extending CrudRepository versus JpaRepository?
  • How do you handle pagination and sorting in Spring Data JPA?
Practice this question with AI feedback →
What is the difference between CrudRepository and JpaRepository?
easy

What they're really asking

This tests your understanding of Spring Data JPA's repository hierarchy and when to choose the right abstraction level for data access needs.

How you'll be scored

Weak

Lists some methods without understanding the inheritance relationship or when to use each.

Average

Correctly identifies that JpaRepository extends CrudRepository and mentions some additional methods.

Strong

Explains the inheritance hierarchy, specific additional methods in JpaRepository, and when to choose each based on application needs.

How to structure your answer

  1. Explain the inheritance relationship between the interfaces.
  2. List the key additional methods JpaRepository provides.
  3. Describe when to use each interface.
  4. Mention performance and functionality trade-offs.

Key points to hit

  • JpaRepository extends PagingAndSortingRepository, which extends CrudRepository.
  • JpaRepository adds batch operations like deleteInBatch() and saveAllAndFlush()
  • JpaRepository includes findAll() that returns List instead of Iterable.
  • Choose CrudRepository for simple CRUD, JpaRepository when you need JPA-specific features.

Common mistakes

  • Saying they're completely different interfaces rather than understanding the inheritance.
  • Not mentioning the performance implications of batch operations in JpaRepository.

Sample answer

JpaRepository extends CrudRepository through the inheritance chain, so it includes all CRUD operations plus additional JPA-specific methods. The key differences are that JpaRepository provides batch operations like deleteInBatch() and saveAllAndFlush(), plus it returns List instead of Iterable for findAll().

I typically use CrudRepository when I only need basic CRUD operations to keep the interface minimal, but choose JpaRepository when I need batch operations or the convenience of working with List collections directly.

How to level up

  • Mention PagingAndSortingRepository as the middle layer that adds pagination support.
  • Discuss how batch operations in JpaRepository can improve performance for bulk operations.
  • Explain that you can create custom repository interfaces extending only the methods you need.

Follow-up questions to expect

  • When would you create a custom repository interface instead of using these built-in ones?
  • How do the batch operations in JpaRepository improve performance?
  • What's the difference between delete() and deleteInBatch()?
Practice this question with AI feedback →
How do you connect a Spring Boot application to a database using JDBC?
easy

What they're really asking

This tests your knowledge of basic database connectivity in Spring Boot and whether you understand both auto-configuration and manual JDBC setup.

How you'll be scored

Weak

Mentions adding dependencies but doesn't understand the connection between configuration properties and DataSource creation.

Average

Correctly lists the dependency and basic application.properties configuration needed.

Strong

Explains the auto-configuration process, shows proper configuration, and mentions connection pooling and alternative configuration methods.

How to structure your answer

  1. Add the JDBC starter dependency.
  2. Configure database connection properties.
  3. Explain how Spring Boot auto-configures DataSource.
  4. Show how to use JdbcTemplate for database operations.

Key points to hit

  • Add spring-boot-starter-jdbc dependency to enable JDBC support.
  • Configure database URL, username, password in application.properties.
  • Spring Boot auto-configures DataSource and JdbcTemplate beans.
  • HikariCP is the default connection pool in Spring Boot.

Common mistakes

  • Forgetting to include the database driver dependency along with the JDBC starter.
  • Not understanding that Spring Boot automatically creates DataSource from properties.

Sample answer

First, I add spring-boot-starter-jdbc dependency and the specific database driver like MySQL or PostgreSQL to my pom.xml. Then I configure the connection in application.properties with spring.datasource.url, spring.datasource.username, and spring.datasource.password. Spring Boot automatically creates a DataSource bean and configures HikariCP connection pooling.

I can then inject JdbcTemplate anywhere in my application to execute SQL queries, and Spring Boot handles all the connection management for me.

How to level up

  • Explain how to configure multiple DataSources using @Primary and @Qualifier annotations.
  • Mention that you can switch connection pools by excluding HikariCP and adding Tomcat or Commons DBCP2.
  • Show how to use @ConfigurationProperties for more complex DataSource configuration.

Follow-up questions to expect

  • How would you configure multiple databases in the same Spring Boot application?
  • What connection pool does Spring Boot use by default and how can you change it?
  • How do you handle database migrations in Spring Boot applications?
Practice this question with AI feedback →

Ready to put this into practice?

Try these questions in a mock interview →

Still applying for jobs? Let Auto Apply do it

Spring Data JPA (Intermediate) (12)

What is the @Entity annotation?
medium

What they're really asking

This tests whether you understand JPA entity mapping fundamentals and how Spring Boot integrates with JPA for object-relational mapping.

How you'll be scored

Weak

Says it marks a class as a database entity but doesn't understand the JPA lifecycle or requirements.

Average

Correctly explains it's a JPA annotation that maps classes to database tables with basic requirements.

Strong

Explains JPA entity lifecycle, required annotations like @Id, and how Spring Boot auto-configures entity scanning.

How to structure your answer

  1. Define what @Entity does in JPA context.
  2. Explain the mapping between class and database table.
  3. List the requirements for a valid entity class.
  4. Show how Spring Boot discovers and manages entities.

Key points to hit

  • @Entity marks a class as a JPA entity that maps to a database table.
  • Entity classes must have a no-arg constructor and an @Id field.
  • Spring Boot automatically scans for entities in the main application package and sub-packages.
  • Entities are managed by the EntityManager and participate in JPA lifecycle.

Common mistakes

  • Thinking @Entity is Spring-specific rather than understanding it's a JPA standard annotation.
  • Not knowing that entities require a no-argument constructor and primary key field.

Sample answer

The @Entity annotation is a JPA annotation that marks a class as a persistent entity that maps to a database table. When I annotate a class with @Entity, Spring Boot's auto-configuration automatically detects it during component scanning and registers it with the EntityManager.

The entity class must have a no-argument constructor and at least one field annotated with @Id to serve as the primary key. Spring Boot uses this information to generate the appropriate database schema through Hibernate's DDL generation.

How to level up

  • Explain how @Table annotation can customize the table name and schema.
  • Mention entity lifecycle callbacks like @PrePersist and @PostLoad.
  • Discuss how Spring Boot's @EntityScan can customize entity scanning packages.

Follow-up questions to expect

  • What other annotations are commonly used with @Entity?
  • How does Spring Boot handle entity scanning and what if your entities are in a different package?
  • What's the difference between @Entity and @Table annotations?
Practice this question with AI feedback →
What is the @Transactional annotation and how does it work?
medium

What they're really asking

This tests your understanding of Spring's declarative transaction management and whether you know how AOP proxies handle transaction boundaries.

How you'll be scored

Weak

Says it handles transactions but doesn't understand how proxy-based AOP works or transaction propagation.

Average

Correctly explains it manages transactions declaratively and mentions rollback behavior.

Strong

Explains AOP proxy mechanism, transaction propagation levels, rollback rules, and common gotchas like self-invocation.

How to structure your answer

  1. Explain declarative transaction management concept.
  2. Describe how Spring AOP proxies intercept method calls.
  3. Cover transaction propagation and isolation levels.
  4. Discuss rollback behavior and exception handling.

Key points to hit

  • @Transactional enables declarative transaction management through AOP proxies.
  • Spring creates proxy objects that intercept method calls to begin/commit/rollback transactions.
  • By default, transactions rollback only on unchecked exceptions (RuntimeException and Error)
  • Transaction propagation controls how methods participate in existing transactions.

Common mistakes

  • Not understanding that @Transactional only works when called through Spring proxies, not for self-invocation.
  • Assuming all exceptions cause rollback when checked exceptions don't by default.

Sample answer

The @Transactional annotation enables declarative transaction management where Spring creates AOP proxies around annotated methods. When I call a @Transactional method, the proxy intercepts the call, starts a transaction, executes the method, and commits or rolls back based on the outcome.

By default, it only rolls back on unchecked exceptions like RuntimeException, but I can configure rollbackFor to include checked exceptions. The annotation supports different propagation levels like REQUIRED or REQUIRES_NEW to control how methods participate in existing transactions.

How to level up

  • Explain the self-invocation problem and how @Transactional doesn't work for internal method calls.
  • Mention that @Transactional can be configured at class level with method-level overrides.
  • Discuss how transaction isolation levels affect concurrent access and performance.

Follow-up questions to expect

  • Why doesn't @Transactional work when you call a method from within the same class?
  • What's the difference between transaction propagation REQUIRED and REQUIRES_NEW?
  • How do you handle transactions that span multiple databases?
Practice this question with AI feedback →
Why does @Transactional sometimes not work in Spring Boot?
medium

What they're really asking

This tests your debugging skills and understanding of common @Transactional pitfalls that cause transactions to not work as expected in production.

How you'll be scored

Weak

Mentions it might not work but doesn't understand the underlying proxy mechanism or specific failure scenarios.

Average

Identifies self-invocation or method visibility as common causes.

Strong

Explains multiple failure scenarios including proxy limitations, exception handling, and configuration issues with specific solutions.

How to structure your answer

  1. Explain the most common cause: self-invocation bypassing proxies.
  2. Cover method visibility requirements for proxy creation.
  3. Discuss exception handling and rollback configuration.
  4. Mention transaction manager configuration issues.

Key points to hit

  • Self-invocation bypasses Spring proxies since this.method() doesn't go through the proxy.
  • Private, final, or static methods can't be proxied and @Transactional won't work.
  • Checked exceptions don't trigger rollback unless explicitly configured with rollbackFor.
  • Missing or misconfigured PlatformTransactionManager can disable transaction management.

Common mistakes

  • Not understanding that Spring AOP uses proxies which have specific limitations.
  • Catching exceptions without rethrowing them, which prevents rollback detection.

Sample answer

The most common reason @Transactional doesn't work is self-invocation where I call a transactional method from within the same class using this.method(). This bypasses the Spring proxy that handles transactions. Also, @Transactional only works on public methods because Spring AOP can't proxy private or final methods.

Another issue is exception handling - if I catch and swallow exceptions or deal with checked exceptions, the transaction won't rollback unless I configure rollbackFor explicitly. Finally, if there's no proper PlatformTransactionManager configured, transactions won't work at all.

How to level up

  • Use @Async with @Transactional requires careful consideration since they create separate threads.
  • ApplicationContextAware or @Autowired self-injection can solve self-invocation issues.
  • Testing with @Transactional behaves differently and may hide these issues during development.

Follow-up questions to expect

  • How would you fix the self-invocation problem with @Transactional?
  • What happens when you use @Transactional with @Async methods?
  • How do you debug transaction boundaries in a running Spring Boot application?
Practice this question with AI feedback →
What is the N+1 query problem and how do you solve it?
medium

What they're really asking

This tests whether you understand performance implications of JPA queries and can identify common database anti-patterns that devastate production systems.

How you'll be scored

Weak

Vague description of 'too many queries' without explaining the specific cause or solutions.

Average

Correctly identifies the problem but only suggests basic solutions like fetch joins without understanding trade-offs.

Strong

Explains the root cause, demonstrates multiple solution approaches, and discusses when each solution is appropriate for production systems.

How to structure your answer

  1. Define what N+1 query problem is with a concrete example.
  2. Explain why it happens in JPA/Hibernate.
  3. Present multiple solution approaches.
  4. Discuss trade-offs and when to use each solution.
  5. Mention monitoring and detection strategies.

Key points to hit

  • N+1 occurs when fetching a collection triggers one query for the list plus N queries for each item's associations.
  • Spring Data JPA's @Query with JOIN FETCH is the most direct solution.
  • EntityGraph provides declarative control over fetch strategies.
  • Batch fetching can reduce queries without changing fetch strategy.

Common mistakes

  • Suggesting EAGER fetching as the primary solution, which can cause worse performance problems.
  • Not understanding that the problem occurs at query time, not mapping time.

Sample answer

The N+1 problem happens when you fetch a list of entities and each entity triggers additional queries to load its associations. For example, if I load 10 orders and each order fetches its customer separately, I get 1 query for orders plus 10 queries for customers.

I solve this using @Query with JOIN FETCH to eagerly load associations in a single query, or @EntityGraph to declaratively specify what to fetch. For scenarios where I can't predict the associations needed, I use Hibernate's batch fetching with hibernate.default_batch_fetch_size to group multiple queries together.

How to level up

  • Use Hibernate's query logging to detect N+1 problems in development before they hit production.
  • Consider using @BatchSize annotation for fine-grained control over batch fetching per entity.
  • Profile your queries with tools like p6spy to measure the actual performance impact.

Follow-up questions to expect

  • How would you detect N+1 queries in a running application?
  • What's the difference between JOIN FETCH and @EntityGraph?
  • When would you choose batch fetching over JOIN FETCH?
Practice this question with AI feedback →
What is the difference between FetchType.LAZY and FetchType.EAGER?
medium

What they're really asking

This tests your understanding of JPA lazy loading mechanics and whether you can make informed decisions about data fetching strategies in production applications.

How you'll be scored

Weak

Basic definition without understanding when each strategy is used or their performance implications.

Average

Correctly explains the difference but doesn't address the trade-offs or practical considerations.

Strong

Demonstrates understanding of both strategies, explains performance trade-offs, and knows how to configure them appropriately for different use cases.

How to structure your answer

  1. Define LAZY vs EAGER loading behavior.
  2. Explain the default fetch types for different association types.
  3. Discuss performance implications of each approach.
  4. Show how to override defaults with annotations.
  5. Address when to use each strategy.

Key points to hit

  • LAZY loading fetches data on first access while EAGER loads immediately with the parent entity.
  • @OneToMany and @ManyToMany default to LAZY, @OneToOne and @ManyToOne default to EAGER.
  • EAGER can cause performance issues by loading unnecessary data.
  • LAZY requires an active Hibernate session to work.

Common mistakes

  • Thinking LAZY always means better performance without considering the context.
  • Not understanding that LAZY loading requires an active persistence context.

Sample answer

LAZY loading defers fetching associated entities until you actually access them, while EAGER loading fetches everything immediately. By default, @OneToMany collections use LAZY because loading all related entities upfront would be expensive, but @ManyToOne uses EAGER since it's typically just one entity.

I prefer LAZY as the default because it avoids loading unnecessary data, but I need to ensure the persistence context is still active when accessing lazy properties. For specific use cases where I know I'll need the data, I use @EntityGraph or JOIN FETCH to eagerly load only what's needed.

How to level up

  • Use @LazyToOne(LazyToOneOption.NO_PROXY) to enable true lazy loading for @OneToOne associations.
  • Consider the View pattern where you define different fetch strategies for different use cases.
  • Monitor your application for LazyInitializationExceptions as indicators of incorrect fetch strategy choices.

Follow-up questions to expect

  • How do you handle lazy loading in a stateless web application?
  • What happens if you try to access a lazy property after the session is closed?
  • How would you implement selective eager loading for a REST API?
Practice this question with AI feedback →
Why does LazyInitializationException occur and how do you fix it?
medium

What they're really asking

This tests whether you understand Hibernate session management and can troubleshoot one of the most common JPA runtime exceptions in web applications.

How you'll be scored

Weak

Basic recognition of the exception without understanding the underlying session lifecycle issues.

Average

Explains the session closure problem but only suggests basic solutions like EAGER fetching.

Strong

Demonstrates deep understanding of persistence context lifecycle and provides multiple context-appropriate solutions.

How to structure your answer

  1. Explain what LazyInitializationException means.
  2. Describe when and why it occurs in web applications.
  3. Present multiple solution strategies.
  4. Discuss which solutions fit different architectural patterns.
  5. Address prevention through proper design.

Key points to hit

  • Exception occurs when accessing lazy properties after the Hibernate session is closed.
  • @Transactional on service methods keeps the session open during the entire operation.
  • JOIN FETCH in queries eliminates the need for lazy loading.
  • Open Session in View pattern extends session to the presentation layer but has drawbacks.

Common mistakes

  • Using Open Session in View pattern without understanding its impact on connection pooling and transaction boundaries.
  • Changing everything to EAGER fetch type as a blanket solution.

Sample answer

LazyInitializationException happens when you try to access a lazy-loaded property after the Hibernate session has closed, typically in controllers or view layers. The cleanest fix is adding @Transactional to your service method so the session stays open for the entire business operation.

If that's not sufficient, I use JOIN FETCH in my repository queries to load the needed associations upfront. I avoid the Open Session in View pattern because it keeps database connections open longer and makes it harder to reason about transaction boundaries, though it can work for read-heavy applications.

How to level up

  • Use DTO projections to explicitly define what data views need, eliminating lazy loading concerns.
  • Configure Hibernate's enable_lazy_load_no_trans for legacy applications, but understand it opens new sessions which bypasses first-level cache.
  • Consider using @EntityGraph with Spring Data JPA's findBy methods for declarative fetch control.

Follow-up questions to expect

  • What are the downsides of using Open Session in View?
  • How would you design a service layer to prevent these exceptions?
  • What's the difference between @Transactional(readOnly=true) and regular @Transactional for lazy loading?
Practice this question with AI feedback →
How is Hibernate chosen as the default JPA implementation without explicit configuration?
medium

What they're really asking

This tests your understanding of Spring Boot's auto-configuration mechanism and whether you grasp how convention-over-configuration works in practice.

How you'll be scored

Weak

Vague answer about Spring Boot 'automatically configuring things' without explaining the actual mechanism.

Average

Mentions auto-configuration but doesn't explain the conditions or how dependencies influence implementation selection.

Strong

Explains the auto-configuration process, conditional annotations, and how Spring Boot selects Hibernate based on classpath detection.

How to structure your answer

  1. Explain Spring Boot's auto-configuration mechanism.
  2. Describe how JPA starter brings in Hibernate dependency.
  3. Show the conditional logic that activates Hibernate.
  4. Discuss how to override or change the implementation.
  5. Address the convention-over-configuration philosophy.

Key points to hit

  • spring-boot-starter-data-jpa includes Hibernate as a transitive dependency by default.
  • @ConditionalOnClass annotations activate Hibernate configuration when classes are present on classpath.
  • HibernateJpaAutoConfiguration automatically creates EntityManagerFactory and related beans.
  • You can exclude Hibernate and include other JPA providers like EclipseLink if needed.

Common mistakes

  • Thinking Hibernate is part of the JPA specification rather than an implementation.
  • Not understanding that auto-configuration is conditional and can be overridden.

Sample answer

When I add spring-boot-starter-data-jpa to my project, it includes Hibernate as a transitive Maven dependency. Spring Boot's auto-configuration kicks in through HibernateJpaAutoConfiguration, which uses @ConditionalOnClass to detect Hibernate classes on the classpath. Once detected, it automatically creates the EntityManagerFactory, PlatformTransactionManager, and other JPA beans using sensible defaults.

If I wanted a different JPA provider, I'd exclude Hibernate from the starter and add EclipseLink or OpenJPA instead. This demonstrates Spring Boot's convention-over-configuration approach where the most common choice becomes the zero-configuration default.

How to level up

  • Use @AutoConfigurationImport to see exactly which auto-configuration classes are being applied.
  • Check the spring-boot-autoconfigure JAR's META-INF/spring.factories to understand all available auto-configurations.
  • Use application properties like spring.jpa.show-sql=true to customize Hibernate without Java configuration.

Follow-up questions to expect

  • How would you switch from Hibernate to EclipseLink in Spring Boot?
  • What happens if you have multiple JPA providers on the classpath?
  • How can you see which auto-configurations are being applied to your application?
Practice this question with AI feedback →
What are derived query methods in Spring Data JPA?
medium

What they're really asking

This tests whether you understand Spring Data JPA's query derivation mechanism and can leverage it effectively to reduce boilerplate repository code.

How you'll be scored

Weak

Basic mention of 'automatic query generation' without understanding the naming conventions or limitations.

Average

Correctly explains the concept with simple examples but doesn't address complex scenarios or trade-offs.

Strong

Demonstrates understanding of query derivation rules, shows complex examples, and knows when to use custom queries instead.

How to structure your answer

  1. Define derived query methods and their purpose.
  2. Show examples of method naming conventions.
  3. Explain how Spring Data JPA parses method names into queries.
  4. Discuss limitations and when to use @Query instead.
  5. Address performance considerations.

Key points to hit

  • Method names are parsed using keywords like findBy, countBy, deleteBy followed by property names.
  • Supports complex expressions with And, Or, Between, Like, GreaterThan, etc.
  • Property expressions can traverse relationships using underscore or camel case.
  • Spring Data JPA generates JPQL queries automatically based on entity metadata.

Common mistakes

  • Creating overly complex method names that are hard to read and maintain.
  • Not understanding that derived queries are parsed at startup, so typos cause application startup failures.

Sample answer

Derived query methods let me create repository queries just by following naming conventions in method signatures. For example, findByFirstNameAndLastName automatically generates a query to search by both name fields, while findByCreatedDateBetween creates a date range query. Spring Data JPA parses these method names at startup and generates the corresponding JPQL.

I can traverse relationships like findByAddressCity to query nested properties. However, for complex queries with joins or custom logic, I switch to @Query annotations because derived method names can become unreadable, and some operations like native SQL aren't supported through method derivation.

How to level up

  • Use the @Query annotation's nativeQuery=true for performance-critical queries that need database-specific optimizations.
  • Leverage Spring Data JPA's Specification interface for dynamic query building when method derivation isn't flexible enough.
  • Consider using @Modifying with derived delete or update methods, but remember they bypass the first-level cache.

Follow-up questions to expect

  • How would you handle a query that needs custom sorting logic?
  • What's the performance difference between derived queries and @Query methods?
  • How do you handle optional parameters in derived query methods?
Practice this question with AI feedback →
What is the @Query annotation for custom queries?
medium

What they're really asking

The interviewer wants to see if you can go beyond Spring Data's derived query methods and write custom queries when the method name convention cannot express the query you need.

How you'll be scored

Weak

Does not know how to write custom queries in Spring Data repositories.

Average

Knows @Query exists for JPQL but does not discuss native queries, named parameters, or modifying queries.

Strong

Demonstrates JPQL and native query usage, parameter binding strategies, pagination support, and modifying queries with @Modifying.

How to structure your answer

  1. Define @Query and when it is needed over derived queries.
  2. Show JPQL query examples.
  3. Explain native SQL queries with nativeQuery = true.
  4. Discuss parameter binding and modifying queries.

Key points to hit

  • @Query lets you define custom JPQL or native SQL queries directly on repository interface methods when derived query method names become too complex.
  • JPQL queries reference entity class names and fields (SELECT u FROM User u) while native queries use actual table and column names.
  • Parameters can be bound by position (?1, ?2) or by name (:name) with @Param annotation, with named parameters being the preferred approach.
  • @Modifying combined with @Query is required for UPDATE and DELETE queries, and must be paired with @Transactional.

Common mistakes

  • Forgetting @Modifying on UPDATE and DELETE queries, which causes Spring Data to try to execute them as SELECT queries.
  • Using native queries unnecessarily when JPQL handles the case, which ties your code to a specific database vendor.

Sample answer

@Query is the annotation you put on a repository method when derived query method names cannot express your query or would be unreadably long. You write JPQL by default, which operates on entity names and fields. For example, @Query("SELECT u FROM User u WHERE u.email LIKE %:domain") with a @Param("domain") parameter.

If I need database-specific features like full-text search, I use @Query(value = "SELECT * FROM users WHERE MATCH(name) AGAINST(:term)", nativeQuery = true). For UPDATE and DELETE operations, I add @Modifying alongside @Query and ensure the calling service method has @Transactional. I also use @Query with Pageable parameters to get paginated results from custom queries.

One thing I always do is use named parameters with @Param instead of positional parameters because they are more readable and less error-prone when query parameters change order.

How to level up

  • Mention SpEL expressions in @Query for dynamic entity names using #{#entityName} for generic repositories.
  • Discuss @Query with projections to return DTOs directly instead of full entities for read-only queries.
  • Explain how to use @Query with Sort parameter for dynamic ordering that combines custom queries with Spring Data sorting.

Follow-up questions to expect

  • What is the difference between JPQL and Criteria API?
  • How do you handle dynamic queries where the WHERE clause changes based on input?
  • When would you use a native query instead of JPQL?
Practice this question with AI feedback →
What is the difference between JPQL and native SQL queries in Spring Data?
medium

What they're really asking

The interviewer wants to see if you understand the abstraction layers in JPA and can make informed decisions about when to use each query type.

How you'll be scored

Weak

Cannot distinguish between JPQL and SQL or does not know both are available in Spring Data.

Average

Correctly explains that JPQL uses entity names and SQL uses table names but misses the portability and feature trade-offs.

Strong

Articulates the abstraction difference, portability implications, performance considerations, and scenarios where each is the right choice.

How to structure your answer

  1. Define JPQL as the JPA Query Language that works on entities.
  2. Define native SQL as raw database queries.
  3. Compare the key differences in a structured way.
  4. Provide guidance on when to use each.

Key points to hit

  • JPQL operates on entity class names and field names (SELECT u FROM User u WHERE u.name = :name) and is database-agnostic.
  • Native SQL uses actual table and column names (SELECT * FROM users WHERE name = :name) and is database-specific.
  • JPQL queries are validated at application startup and integrated with JPA caching, while native queries bypass these features.
  • Native queries are necessary for database-specific features like window functions, full-text search, or complex joins that JPQL cannot express.

Common mistakes

  • Always defaulting to native queries because you are more comfortable with SQL, which sacrifices portability and JPA cache integration.
  • Not knowing that JPQL supports joins, subqueries, and aggregate functions, which covers most query needs without dropping to native SQL.

Sample answer

JPQL is JPA's query language that operates on entity objects and their fields, not database tables and columns. When I write @Query("SELECT u FROM User u WHERE u.department.name = :dept"), JPQL navigates the object graph and JPA generates the correct SQL with joins.

It is database-agnostic, so if I switch from PostgreSQL to MySQL, my JPQL queries work without changes. Native SQL uses @Query with nativeQuery = true and actual table and column names.

I use it when I need database-specific features like PostgreSQL's jsonb operators, full-text search with MATCH AGAINST, or complex window functions that JPQL cannot express. The trade-off is clear: JPQL gives you portability and JPA cache integration, while native SQL gives you access to the full power of your database engine.

In practice, about 90% of my queries are JPQL or derived methods, and I only drop to native SQL for reporting queries or database-specific optimizations.

How to level up

  • Mention that JPQL queries are parsed at startup and catch errors early, while native query errors may only surface at runtime.
  • Discuss using SqlResultSetMapping for mapping native query results to non-entity DTOs.
  • Explain that Hibernate's HQL extends JPQL with additional features like window functions in newer versions.

Follow-up questions to expect

  • How do you map native query results to a custom DTO?
  • Can JPQL queries take advantage of database-specific indexes?
  • What is the Criteria API and how does it compare to both JPQL and native SQL?
Practice this question with AI feedback →
What are the types of transaction management Spring supports?
medium

What they're really asking

The interviewer wants to see if you understand how Spring manages database transactions and can choose the appropriate approach for your application architecture.

How you'll be scored

Weak

Does not know the difference between programmatic and declarative transaction management.

Average

Explains declarative transactions with @Transactional but does not discuss programmatic management or the underlying PlatformTransactionManager.

Strong

Explains both approaches with concrete examples, understands the underlying TransactionManager abstraction, and knows when programmatic control is necessary.

How to structure your answer

  1. Explain declarative transaction management with @Transactional.
  2. Explain programmatic transaction management with TransactionTemplate.
  3. Discuss the PlatformTransactionManager abstraction.
  4. Recommend when to use each approach.

Key points to hit

  • Declarative transaction management uses @Transactional annotation and AOP proxies to manage transactions without writing transaction code in business logic.
  • Programmatic transaction management uses TransactionTemplate or PlatformTransactionManager API for fine-grained, explicit control within methods.
  • Both approaches use PlatformTransactionManager as the underlying abstraction, with implementations like JpaTransactionManager and DataSourceTransactionManager.
  • @Transactional supports propagation, isolation, timeout, readOnly, and rollbackFor attributes for controlling transaction behavior.

Common mistakes

  • Not understanding that @Transactional works through AOP proxies, so calling a @Transactional method from within the same class bypasses the proxy and the transaction.
  • Using programmatic transaction management everywhere when @Transactional handles 95% of cases more cleanly.

Sample answer

Spring supports two types of transaction management. Declarative is the most common, where I annotate service methods with @Transactional and Spring handles begin, commit, and rollback through AOP proxies. I configure propagation behavior with @Transactional(propagation = Propagation.REQUIRES_NEW) and rollback rules with rollbackFor = Exception.class.

For cases where I need fine-grained control within a method, I use programmatic management with TransactionTemplate. For example, if I need to commit one operation and then start a separate transaction for another within the same method, TransactionTemplate.execute() gives me that control. Both approaches use the PlatformTransactionManager abstraction underneath.

Spring Boot auto-configures the right implementation: JpaTransactionManager when using JPA, or DataSourceTransactionManager for plain JDBC. The critical thing to understand is that @Transactional only works when called through the Spring proxy, not when calling the method internally within the same class.

How to level up

  • Mention the self-invocation problem and how to work around it using AopContext.currentProxy() or restructuring to call from another bean.
  • Discuss @Transactional(readOnly = true) which optimizes read operations by hinting the persistence provider to skip dirty checking.
  • Explain how distributed transactions work with JtaTransactionManager for coordinating multiple data sources.

Follow-up questions to expect

  • What happens when you call a @Transactional method from the same class?
  • How do you configure transaction isolation levels in Spring?
  • What is the difference between REQUIRES_NEW and NESTED propagation?
Practice this question with AI feedback →
What is the significance of the @Repository annotation beyond being a stereotype?
medium

What they're really asking

The interviewer wants to see if you understand the technical behavior that @Repository adds beyond simple bean registration, specifically persistence exception translation.

How you'll be scored

Weak

Thinks @Repository is just a label with no technical behavior.

Average

Mentions exception translation but cannot explain how it works or why it matters.

Strong

Explains the PersistenceExceptionTranslationPostProcessor mechanism, the DataAccessException hierarchy, and why this decouples your code from specific persistence implementations.

How to structure your answer

  1. Acknowledge @Repository as a stereotype annotation for component scanning.
  2. Explain the persistence exception translation feature.
  3. Describe the DataAccessException hierarchy.
  4. Discuss why this matters for application architecture.

Key points to hit

  • @Repository enables automatic persistence exception translation through PersistenceExceptionTranslationPostProcessor.
  • It converts technology-specific exceptions (JDBC SQLException, JPA PersistenceException, Hibernate HibernateException) into Spring's DataAccessException hierarchy.
  • This decoupling means your service layer catches Spring exceptions regardless of whether you use JDBC, JPA, or MongoDB underneath.
  • Spring Boot auto-configures the exception translation post-processor, so @Repository activates this behavior automatically.

Common mistakes

  • Thinking @Repository has no technical significance beyond @Component, which is a common misconception.
  • Not understanding that Spring Data JPA repository interfaces already get this behavior without explicit @Repository annotation.

Sample answer

Beyond being a stereotype for component scanning, @Repository enables automatic persistence exception translation. When you annotate a class with @Repository, Spring wraps it with an AOP proxy that catches technology-specific persistence exceptions like JDBC's SQLException, JPA's PersistenceException, or Hibernate's HibernateException. It translates them into Spring's DataAccessException hierarchy, which has specific subclasses like DataIntegrityViolationException and OptimisticLockingFailureException.

This matters because my service layer can catch Spring exceptions without being tied to a specific persistence technology. If I switch from JPA to JDBC Template or even to MongoDB, the service layer code does not change because it catches DataAccessException, not JPA-specific exceptions.

One thing to note is that Spring Data JPA repository interfaces get this behavior automatically without the @Repository annotation because the framework infrastructure applies it.

How to level up

  • Mention that the translation is handled by PersistenceExceptionTranslationPostProcessor which Spring Boot auto-configures.
  • Discuss that you can create custom exception translators by implementing PersistenceExceptionTranslator.
  • Explain how this fits into the broader principle of abstracting away infrastructure concerns from business logic.

Follow-up questions to expect

  • What is the DataAccessException hierarchy in Spring?
  • Do Spring Data JPA interfaces need the @Repository annotation?
  • How would you create a custom persistence exception translator?
Practice this question with AI feedback →

Spring Data JPA (Advanced) (7)

Why is spring.jpa.hibernate.ddl-auto=update not recommended in production?
hard

What they're really asking

The interviewer wants to see if you understand safe database schema management practices and have production experience where uncontrolled schema changes can cause data loss or outages.

How you'll be scored

Weak

Does not understand what ddl-auto=update does or sees nothing wrong with using it in production.

Average

Knows it modifies the schema automatically but cannot articulate the specific risks or the recommended alternatives.

Strong

Explains the specific dangers of automatic schema modification, gives concrete scenarios where it fails, and recommends migration tools like Flyway or Liquibase.

How to structure your answer

  1. Explain what ddl-auto=update does.
  2. List the specific risks in production.
  3. Describe scenarios where it causes problems.
  4. Recommend the proper alternative.

Key points to hit

  • ddl-auto=update tells Hibernate to compare entity mappings with the database schema at startup and apply additive changes like new columns and tables.
  • It never drops columns, tables, or constraints, so schema drift accumulates as orphaned columns and indexes over time.
  • It cannot handle complex migrations like renaming columns, splitting tables, or data transformations, which require explicit migration scripts.
  • It runs without version control, rollback capability, or audit trail, making it impossible to track or revert schema changes.

Common mistakes

  • Using ddl-auto=update because it works in development and assuming it will work the same way in production.
  • Not understanding that Hibernate's schema update is additive only and cannot remove or rename existing database objects.

Sample answer

spring.jpa.hibernate.ddl-auto=update works well in development, but it is dangerous in production for several reasons. First, it runs automatically at startup without any review or approval process. If someone pushes a bad entity change, Hibernate modifies the production schema immediately. Second, it only adds things. It cannot drop unused columns, rename fields, or handle data migrations.

Over time, your schema accumulates orphaned columns and tables that no entity maps to. Third, there is no version control or rollback capability. If the update breaks something, you cannot easily revert. Fourth, on large tables, adding a column with ALTER TABLE can lock the table for minutes, causing downtime.

In production, I always set ddl-auto=none or validate and use Flyway or Liquibase for schema migrations. These tools give me versioned, reviewable migration scripts that can be tested in staging, rolled back if needed, and tracked in source control alongside the application code.

How to level up

  • Mention that ddl-auto=validate is a good production choice because it verifies the schema matches your entities at startup without modifying anything.
  • Discuss blue-green deployment strategies where schema migrations are applied as a separate step before the application deployment.
  • Explain how to generate initial Flyway migration scripts from an existing Hibernate-managed schema using hbm2ddl export.

Follow-up questions to expect

  • What is the difference between ddl-auto values: none, validate, update, and create-drop?
  • How do you handle database migrations that require data transformations?
  • How do you coordinate schema changes with zero-downtime deployments?
Practice this question with AI feedback →
How do you implement database migration with Flyway or Liquibase in Spring Boot?
hard

What they're really asking

This tests understanding of database schema versioning in production Spring Boot applications and whether you can implement controlled database evolution without downtime or data loss.

How you'll be scored

Weak

Mentions migration tools but can't explain the actual implementation or Spring Boot integration specifics.

Average

Correctly describes basic Flyway or Liquibase setup with Spring Boot but misses production concerns like rollback strategies.

Strong

Demonstrates understanding of migration scripts, versioning strategies, rollback procedures, and environment-specific considerations.

How to structure your answer

  1. Choose and justify migration tool (Flyway vs Liquibase)
  2. Show Spring Boot dependency and configuration setup.
  3. Explain migration script organization and naming.
  4. Address rollback and production deployment strategies.
  5. Discuss validation and testing approaches.

Key points to hit

  • Flyway uses SQL-based migrations with version numbering, while Liquibase supports multiple formats and has more advanced rollback capabilities.
  • Spring Boot auto-configuration handles migration execution on startup when dependencies are present.
  • Migration scripts should be immutable once deployed and follow naming conventions like V1__Initial_schema.sql.
  • Production deployments require careful consideration of migration timing and potential rollback scenarios.

Common mistakes

  • Assuming migrations always run successfully without planning for failures or rollbacks.
  • Not understanding that migration scripts become immutable once applied in production environments.

Sample answer

I typically use Flyway for database migrations in Spring Boot because of its simplicity and SQL-first approach. I add the spring-boot-starter-flyway dependency, then create migration scripts in src/main/resources/db/migration following the naming pattern like V1__Create_user_table.sql. Spring Boot automatically runs pending migrations on startup.

For production, I configure flyway.baseline-on-migrate=true for existing databases and set up separate migration scripts for each environment. I always test migrations against production-like data and have rollback procedures documented, though Flyway's paid version handles rollbacks better than the community edition.

How to level up

  • Use Flyway callbacks to execute custom logic before or after migrations, like data transformation scripts.
  • Implement migration validation in your CI/CD pipeline to catch syntax errors before production deployment.
  • Consider using Flyway's repair command for fixing checksum mismatches in development environments.

Follow-up questions to expect

  • How would you handle a migration that needs to run differently in production versus development?
  • What's your strategy for rolling back a migration that caused production issues?
  • How do you coordinate database migrations with application deployments in a microservices architecture?
Practice this question with AI feedback →
What is Spring DAO support?
hard

What they're really asking

This tests knowledge of Spring's data access abstraction layer and whether you understand how Spring simplifies database exception handling and transaction management across different persistence technologies.

How you'll be scored

Weak

Confuses Spring DAO support with Spring Data JPA or can't explain the exception translation mechanism.

Average

Correctly identifies DataAccessException hierarchy and @Repository annotation but lacks depth on the abstraction benefits.

Strong

Explains exception translation, template patterns, and how Spring DAO support enables technology-agnostic data access layers.

How to structure your answer

  1. Define Spring DAO support and its core purpose.
  2. Explain DataAccessException hierarchy and exception translation.
  3. Show @Repository annotation benefits.
  4. Demonstrate template pattern usage (JdbcTemplate, etc.)
  5. Compare with Spring Data JPA modern approaches.

Key points to hit

  • Spring DAO support provides a consistent exception hierarchy through DataAccessException, translating vendor-specific exceptions.
  • @Repository annotation enables automatic exception translation from native database exceptions to Spring's DataAccessException.
  • Template classes like JdbcTemplate eliminate boilerplate code and handle resource management automatically.
  • The abstraction allows switching between persistence technologies without changing exception handling code.

Common mistakes

  • Confusing Spring DAO support (the abstraction layer) with Spring Data JPA (the repository implementation)
  • Not understanding that @Repository does more than just stereotype annotation, it enables exception translation.

Sample answer

Spring DAO support is Spring's data access abstraction that provides a consistent programming model across different persistence technologies. The key feature is exception translation through DataAccessException hierarchy, which converts database-specific exceptions into Spring's unchecked exceptions.

When I use @Repository on my DAO classes, Spring automatically translates SQLException or Hibernate exceptions into more meaningful exceptions like DataIntegrityViolationException. This abstraction means I can switch from JdbcTemplate to JPA without changing my exception handling code.

While Spring Data JPA has largely replaced manual DAO implementations, understanding this foundation helps when you need custom data access logic.

How to level up

  • Implement custom exception translators for database-specific error codes that Spring doesn't handle out of the box.
  • Use @Repository with custom DAO implementations alongside Spring Data JPA repositories for complex queries.
  • Leverage Spring's template patterns in integration tests for setup and teardown operations.

Follow-up questions to expect

  • How does Spring's exception translation work under the hood with different persistence providers?
  • When would you still use JdbcTemplate instead of Spring Data JPA in a modern application?
  • How do you handle database-specific optimizations while maintaining the DAO abstraction?
Practice this question with AI feedback →
How do you implement pagination and sorting with Spring Data JPA?
hard

What they're really asking

This tests practical knowledge of handling large datasets efficiently in Spring applications and whether you understand the performance implications of pagination strategies in production systems.

How you'll be scored

Weak

Only mentions Pageable interface without understanding Sort integration or performance considerations.

Average

Shows correct Pageable and Sort usage but doesn't address performance issues with large offsets or custom implementations.

Strong

Demonstrates understanding of different pagination strategies, performance trade-offs, and when to use cursor-based pagination for large datasets.

How to structure your answer

  1. Show basic Pageable and Sort implementation.
  2. Explain PageRequest creation and parameter binding.
  3. Demonstrate controller integration with @PageableDefault.
  4. Address performance concerns with large offsets.
  5. Present cursor-based pagination as alternative for large datasets.

Key points to hit

  • Pageable interface works with Sort to provide offset-based pagination, integrated automatically with Spring Data JPA repositories.
  • PageRequest.of(page, size, Sort.by()) creates pagination parameters, with pages starting from 0.
  • @PageableDefault annotation in controllers sets reasonable defaults and prevents unbounded queries.
  • Large offset pagination becomes inefficient (SELECT with LIMIT 100000, 20), requiring cursor-based approaches for big datasets.

Common mistakes

  • Using large page sizes or allowing unbounded page sizes, which can cause memory and performance issues.
  • Not understanding that offset-based pagination becomes inefficient with large datasets due to database scanning.

Sample answer

I implement pagination by having my repository methods return Page<T> and accept Pageable parameters. In the controller, I use @PageableDefault(size = 20) to set reasonable limits and inject Pageable directly. For example, userRepository.findByActiveTrue(PageRequest.of(0, 20, Sort.by('lastName'))) returns the first page sorted by last name. The returned Page object includes total count and metadata.

For large datasets over 100k records, I switch to cursor-based pagination using 'where id > lastSeenId limit 20' because offset-based pagination becomes too slow when users navigate to high page numbers.

How to level up

  • Implement cursor-based pagination for large datasets using repository methods that accept a cursor parameter instead of page numbers.
  • Use database-specific pagination optimizations like PostgreSQL's OFFSET FETCH or MySQL's LIMIT with covering indexes.
  • Consider implementing search-after patterns for real-time data where total counts aren't necessary.

Follow-up questions to expect

  • How would you implement pagination for a search API that needs to remain consistent as new data is added?
  • What's your approach to pagination when you need to aggregate data across multiple microservices?
  • How do you handle pagination performance when sorting by non-indexed columns?
Practice this question with AI feedback →
What is the second-level cache in Hibernate and how do you configure it in Spring Boot?
hard

What they're really asking

This tests deep understanding of Hibernate performance optimization and whether you can configure advanced caching strategies to reduce database load in high-traffic Spring Boot applications.

How you'll be scored

Weak

Mentions second-level cache exists but can't explain the difference from first-level cache or show actual configuration.

Average

Correctly describes session vs application-level caching and shows basic Ehcache configuration but misses cache regions and strategies.

Strong

Explains cache levels, demonstrates provider configuration, discusses cache regions, eviction strategies, and distributed caching considerations.

How to structure your answer

  1. Differentiate first-level (session) vs second-level (application) cache.
  2. Show Spring Boot cache provider configuration.
  3. Demonstrate entity and query cache annotations.
  4. Explain cache regions and eviction strategies.
  5. Address distributed caching and invalidation challenges.

Key points to hit

  • Second-level cache operates at SessionFactory level, shared across sessions, while first-level cache is per-session and always enabled.
  • Spring Boot requires explicit cache provider like Ehcache or Redis, plus hibernate.cache.use_second_level_cache=true configuration.
  • @Cacheable and @Cache annotations control entity caching, while query cache requires separate configuration and careful usage.
  • Cache regions allow different eviction policies per entity type, critical for managing memory and data freshness.

Common mistakes

  • Enabling second-level cache for frequently updated entities, which can cause more cache invalidation overhead than database queries.
  • Not configuring appropriate cache regions and eviction policies, leading to memory leaks or stale data issues.

Sample answer

Hibernate's second-level cache is shared across all sessions in the application, unlike the first-level cache which is per-session. In Spring Boot, I configure it by adding Ehcache dependency and setting hibernate.cache.use_second_level_cache=true in application.properties. I annotate read-mostly entities like @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) and configure cache regions in ehcache.xml with appropriate TTL and eviction policies.

For distributed applications, I use Redis as the cache provider since Ehcache is local to each instance. Query cache is separate and requires hibernate.cache.use_query_cache=true, but I'm careful because it invalidates whenever any entity in the query changes.

How to level up

  • Use different cache regions for entities with different update patterns - configure longer TTL for reference data and shorter for transactional data.
  • Monitor cache hit ratios through Hibernate statistics and Spring Boot Actuator to optimize cache configuration.
  • Implement custom cache event listeners for complex invalidation scenarios in distributed systems.

Follow-up questions to expect

  • How do you handle cache invalidation across multiple application instances?
  • What's your strategy for cache warming in a microservices environment?
  • How do you debug cache-related performance issues in production?
Practice this question with AI feedback →
How do you implement auditing (created date, modified date) with Spring Data JPA?
hard

What they're really asking

This tests knowledge of implementing cross-cutting audit concerns and whether you understand how to automatically track entity lifecycle events without cluttering business logic with audit code.

How you'll be scored

Weak

Mentions audit annotations exist but can't show proper configuration or explain the AuditorAware interface.

Average

Shows correct @CreatedDate and @LastModifiedDate usage but doesn't explain AuditorAware or security integration.

Strong

Demonstrates complete audit setup including custom auditor resolution, security integration, and handling of audit data in different scenarios.

How to structure your answer

  1. Enable JPA auditing with @EnableJpaAuditing.
  2. Create base audit entity with audit annotations.
  3. Implement AuditorAware for user tracking.
  4. Show integration with Spring Security.
  5. Address audit data handling and querying strategies.

Key points to hit

  • @EnableJpaAuditing annotation activates audit functionality, working with @CreatedDate, @LastModifiedDate, @CreatedBy, @LastModifiedBy annotations.
  • Base audit entity or @MappedSuperclass provides reusable audit fields across multiple entities.
  • AuditorAware<String> implementation resolves current user from SecurityContext or other authentication sources.
  • Audit fields are automatically populated on persist and update operations without requiring explicit setter calls.

Common mistakes

  • Forgetting @EnableJpaAuditing configuration, which prevents audit annotations from working.
  • Not handling cases where no authenticated user exists, causing null values in audit fields.

Sample answer

I implement auditing by first adding @EnableJpaAuditing to my main application class, then creating a base AuditableEntity with @CreatedDate, @LastModifiedDate, @CreatedBy, and @LastModifiedBy fields. I make my entities extend this base class. For user tracking, I implement AuditorAware<String> that pulls the username from SecurityContextHolder.getContext().getAuthentication(). This bean is automatically detected by Spring.

For system operations where no user exists, I handle null authentication by returning 'SYSTEM' as the auditor. The audit fields are populated automatically on save and update without any explicit code in my service layer.

How to level up

  • Use separate audit tables with Hibernate Envers for complete audit trails including historical changes, not just creation and modification.
  • Implement custom audit event listeners for complex scenarios like auditing related entity changes or business-specific audit requirements.
  • Consider using database-level audit triggers for audit requirements that must survive even direct database modifications.

Follow-up questions to expect

  • How would you implement auditing for bulk operations that bypass JPA entity lifecycle callbacks?
  • What's your approach to auditing in microservices where the user context might come from JWT tokens?
  • How do you handle audit data retention and archiving in high-volume systems?
Practice this question with AI feedback →
What is the difference between optimistic and pessimistic locking in JPA?
hard

What they're really asking

This tests your understanding of JPA concurrency control mechanisms and when to choose each strategy. The interviewer wants to see if you can prevent data corruption in multi-user applications.

How you'll be scored

Weak

Confuses the two concepts or gives incorrect definitions without understanding the trade-offs.

Average

Correctly defines both but lacks examples or understanding of when to use each approach.

Strong

Explains both concepts with concrete examples, discusses performance implications, and knows when to apply each strategy in production.

How to structure your answer

  1. Define optimistic locking and when it assumes conflicts are rare.
  2. Define pessimistic locking and when it prevents conflicts upfront.
  3. Compare performance and use case scenarios.
  4. Provide concrete JPA examples with annotations.
  5. Discuss production implications and trade-offs.

Key points to hit

  • Optimistic locking uses versioning (@Version) and fails fast on conflicts, better for read-heavy scenarios.
  • Pessimistic locking holds database locks during transactions, preventing conflicts but reducing concurrency.
  • Choose optimistic for high-read, low-conflict scenarios; pessimistic for critical updates that cannot fail.
  • Optimistic locking requires proper exception handling for OptimisticLockException.

Common mistakes

  • Not understanding that optimistic locking happens at commit time, not during the transaction.
  • Assuming pessimistic locking is always slower without considering the cost of retry logic.

Sample answer

Optimistic locking assumes conflicts are rare and uses a version field to detect changes at commit time. I use @Version annotation on an entity field, and if another transaction modified the record, JPA throws OptimisticLockException. Pessimistic locking prevents conflicts by holding database locks during the transaction using @Lock(LockModeType.PESSIMISTIC_WRITE).

I choose optimistic for read-heavy scenarios like product catalogs where conflicts are uncommon, and pessimistic for critical operations like inventory updates where retry logic would be complex and costly.

How to level up

  • Discuss custom versioning strategies beyond simple integer versions for distributed systems.
  • Mention how optimistic locking integrates with Spring's @Transactional rollback behavior.
  • Explain how to handle OptimisticLockException gracefully in REST APIs with proper HTTP status codes.

Follow-up questions to expect

  • How would you handle OptimisticLockException in a REST controller?
  • What happens if you forget to include the version field in your update operations?
  • How does pessimistic locking affect database connection pooling?
Practice this question with AI feedback →

Ready to put this into practice?

Try these questions in a mock interview →

Still applying for jobs? Let Auto Apply do it

Spring Security (Beginner) (7)

What is Spring Security?
easy

What they're really asking

This tests your foundational knowledge of Spring Security as a framework. The interviewer wants to see if you understand its core purpose and main capabilities.

How you'll be scored

Weak

Gives a vague answer about security without mentioning specific Spring Security features or capabilities.

Average

Correctly identifies it as a security framework with basic authentication and authorization features.

Strong

Explains Spring Security's comprehensive security model including declarative security, integration capabilities, and production-ready features.

How to structure your answer

  1. Define Spring Security as a comprehensive security framework.
  2. Explain its declarative approach to security.
  3. Mention key features like authentication, authorization, and protection mechanisms.
  4. Discuss integration with Spring Boot auto-configuration.
  5. Touch on production-ready aspects.

Key points to hit

  • Spring Security is a comprehensive security framework providing declarative security for Spring applications.
  • Handles both authentication (who you are) and authorization (what you can do) through filters and AOP.
  • Integrates seamlessly with Spring Boot through auto-configuration and starter dependencies.
  • Provides protection against common vulnerabilities like CSRF, session fixation, and clickjacking out of the box.

Common mistakes

  • Describing it only as authentication without mentioning authorization and other security features.
  • Not understanding that it works through servlet filters, not just annotations.

Sample answer

Spring Security is a comprehensive security framework that provides declarative authentication, authorization, and protection against common vulnerabilities for Spring applications. It works primarily through servlet filters to intercept requests before they reach your controllers.

With Spring Boot, you get auto-configuration that secures all endpoints by default, protects against CSRF attacks, and provides login pages out of the box. It supports multiple authentication mechanisms like form-based, HTTP Basic, OAuth2, and JWT, making it suitable for both web applications and REST APIs.

How to level up

  • Mention its filter chain architecture and how you can customize the security filter order.
  • Discuss how it integrates with external authentication providers and identity management systems.
  • Explain the difference between method-level and URL-level security configuration.

Follow-up questions to expect

  • How does Spring Security's filter chain work?
  • What security features does Spring Boot enable by default?
  • How would you configure Spring Security for a REST API versus a web application?
Practice this question with AI feedback →
What is the difference between authentication and authorization?
easy

What they're really asking

This tests your understanding of fundamental security concepts that underpin Spring Security. The interviewer wants to verify you grasp these core distinctions before diving into implementation details.

How you'll be scored

Weak

Confuses the two concepts or provides incorrect definitions that would lead to security vulnerabilities.

Average

Correctly defines both concepts but without clear examples or understanding of how they work together.

Strong

Clearly explains both concepts with relevant examples and understands how they complement each other in a security system.

How to structure your answer

  1. Define authentication as identity verification.
  2. Define authorization as permission checking.
  3. Explain how they work sequentially in security flow.
  4. Provide concrete examples from Spring Security context.
  5. Mention how they complement each other.

Key points to hit

  • Authentication verifies who you are (identity verification through credentials like username/password)
  • Authorization determines what you can do (permission checking based on roles or authorities)
  • Authentication happens first, then authorization uses the authenticated identity to make access decisions.
  • In Spring Security, authentication is handled by AuthenticationManager, authorization by access control expressions.

Common mistakes

  • Thinking they are the same thing or can be used interchangeably.
  • Not understanding that authorization is meaningless without prior authentication.

Sample answer

Authentication is proving who you are, typically through credentials like username and password, while authorization is determining what you're allowed to do based on that identity. Think of authentication as showing your ID at airport security, and authorization as your boarding pass determining which gate you can access.

In Spring Security, I first authenticate users through mechanisms like form login or JWT tokens, then use role-based authorization with annotations like @PreAuthorize to control access to specific methods or endpoints based on their authorities.

How to level up

  • Explain how stateless authentication (like JWT) affects the relationship between authentication and authorization.
  • Discuss how Spring Security separates authentication logic from authorization through different interfaces.
  • Mention scenarios where you might have authentication without authorization (like public APIs with user tracking)

Follow-up questions to expect

  • How does Spring Security handle these concepts in a stateless REST API?
  • What happens if authentication succeeds but authorization fails?
  • Can you have authorization without authentication in Spring Security?
Practice this question with AI feedback →
What is basic authentication in Spring Security?
easy

What they're really asking

This tests your knowledge of HTTP Basic authentication implementation in Spring Security. The interviewer wants to see if you understand this fundamental authentication mechanism and its trade-offs.

How you'll be scored

Weak

Cannot explain how Basic authentication works or confuses it with other authentication methods.

Average

Correctly describes Basic authentication but lacks understanding of configuration or security implications.

Strong

Explains Basic authentication mechanism, shows how to configure it in Spring Security, and discusses security considerations.

How to structure your answer

  1. Explain HTTP Basic authentication protocol.
  2. Describe how Spring Security implements it.
  3. Show configuration examples.
  4. Discuss security implications and limitations.
  5. Mention when to use versus alternatives.

Key points to hit

  • Basic authentication sends username and password encoded in Base64 in the Authorization header with each request.
  • Spring Security enables it through httpBasic() configuration and it works well for REST APIs.
  • Base64 encoding is not encryption, so HTTPS is mandatory for security.
  • It is stateless, making it suitable for API authentication but requires credentials with every request.

Common mistakes

  • Thinking Base64 encoding provides security (it is just encoding, not encryption)
  • Not understanding that credentials are sent with every request, not just during login.

Sample answer

Basic authentication in Spring Security sends the username and password Base64-encoded in the Authorization header with each request. I configure it using http.httpBasic() in my security configuration, and Spring automatically extracts credentials from the 'Authorization: Basic <encoded-credentials>' header. Since Base64 is just encoding, not encryption, I always use HTTPS in production.

It works well for REST APIs because it is stateless, but I prefer JWT tokens for browser-based applications since users don't want to enter credentials repeatedly.

How to level up

  • Explain how to customize the Basic authentication entry point for better API error responses.
  • Discuss combining Basic authentication with other methods in the same application.
  • Mention how Basic authentication integrates with Spring Security's UserDetailsService.

Follow-up questions to expect

  • How would you secure Basic authentication in production?
  • What are the advantages of Basic authentication over form-based login for APIs?
  • How does Spring Security validate the credentials from the Authorization header?
Practice this question with AI feedback →
What are the primary features of Spring Security?
easy

What they're really asking

This tests your comprehensive understanding of Spring Security's feature set. The interviewer wants to see if you know the breadth of capabilities beyond basic authentication.

How you'll be scored

Weak

Lists only one or two basic features like login without understanding the comprehensive security model.

Average

Mentions several core features but lacks depth about their integration or production value.

Strong

Demonstrates understanding of Spring Security's comprehensive approach including protection mechanisms, integration features, and production concerns.

How to structure your answer

  1. Cover authentication mechanisms and providers.
  2. Explain authorization and access control features.
  3. Discuss built-in protection against common vulnerabilities.
  4. Mention integration and extensibility capabilities.
  5. Touch on production and operational features.

Key points to hit

  • Comprehensive authentication support including form-based, HTTP Basic, OAuth2, JWT, and LDAP integration.
  • Fine-grained authorization through method-level security, URL patterns, and expression-based access control.
  • Built-in protection against CSRF, session fixation, clickjacking, and other OWASP Top 10 vulnerabilities.
  • Seamless integration with Spring ecosystem and extensibility through custom authentication providers and filters.

Common mistakes

  • Focusing only on authentication and ignoring the comprehensive security model.
  • Not mentioning the automatic protection features that work out of the box.

Sample answer

Spring Security provides comprehensive authentication support including form login, HTTP Basic, OAuth2, and JWT tokens, plus integration with external systems like LDAP and Active Directory. For authorization, it offers method-level security with @PreAuthorize, URL-based access control, and role hierarchies. It automatically protects against CSRF attacks, session fixation, and clickjacking without additional configuration.

The framework integrates seamlessly with Spring Boot through auto-configuration and provides extensive customization through security filter chains, making it suitable for everything from simple web apps to complex enterprise systems.

How to level up

  • Discuss the security filter chain architecture and how different features plug into it.
  • Mention Spring Security's testing support with @WithMockUser and security test slices.
  • Explain how Spring Security adapts to different application types (web, reactive, OAuth2 resource servers)

Follow-up questions to expect

  • Which of these features would you prioritize for a REST API versus a web application?
  • How does Spring Security handle session management and concurrent session control?
  • What customizations have you made to Spring Security in production applications?
Practice this question with AI feedback →
What is the UserDetailsService interface?
easy

What they're really asking

This tests understanding of Spring Security's core authentication mechanism and whether you know how to integrate custom user loading logic with the security framework.

How you'll be scored

Weak

Describes it as 'something that loads users' without understanding the authentication flow integration.

Average

Correctly identifies it as the interface for loading user details during authentication with basic implementation knowledge.

Strong

Demonstrates understanding of how UserDetailsService fits into the authentication flow and can discuss custom implementations and caching strategies.

How to structure your answer

  1. Define the interface purpose.
  2. Explain the loadUserByUsername method.
  3. Show how it integrates with authentication.
  4. Discuss common implementations.
  5. Mention production considerations.

Key points to hit

  • UserDetailsService loads user-specific data during authentication.
  • Returns UserDetails object containing authorities and credentials.
  • Spring Security provides built-in implementations like InMemoryUserDetailsManager.
  • Custom implementations typically query databases or external systems.

Common mistakes

  • Confusing UserDetailsService with UserDetails object.
  • Not understanding that it's called during authentication, not authorization.

Sample answer

UserDetailsService is Spring Security's interface for loading user-specific data during authentication. It has one method, loadUserByUsername, which takes a username and returns a UserDetails object containing the user's credentials, authorities, and account status. When a user logs in, Spring Security calls this service to retrieve user information and validate credentials.

I've implemented custom UserDetailsService classes that query our user database and map roles to Spring Security authorities. In production, I always add caching to avoid database hits on every request and implement proper exception handling for user-not-found scenarios.

How to level up

  • Implement caching with @Cacheable to avoid repeated database queries.
  • Consider using UserDetailsManager for full CRUD operations on users.
  • Implement custom UserDetails objects to include additional user properties.

Follow-up questions to expect

  • How would you implement caching for UserDetailsService?
  • What's the difference between UserDetailsService and UserDetailsManager?
  • How do you handle user roles and authorities in your UserDetails implementation?
Practice this question with AI feedback →
What is the PasswordEncoder interface and why is it important?
easy

What they're really asking

This tests knowledge of secure password handling practices and whether you understand why plaintext passwords are a security vulnerability in production systems.

How you'll be scored

Weak

Mentions password encoding without understanding security implications or different encoding strategies.

Average

Correctly explains password encoding/hashing with knowledge of BCrypt and basic security benefits.

Strong

Demonstrates understanding of different encoding algorithms, salt usage, performance trade-offs, and migration strategies between encoders.

How to structure your answer

  1. Define PasswordEncoder's purpose.
  2. Explain encoding vs plain text.
  3. Discuss common implementations.
  4. Cover security benefits.
  5. Address production considerations.

Key points to hit

  • PasswordEncoder handles secure password hashing and verification.
  • BCryptPasswordEncoder is the recommended default with built-in salting.
  • Never store plain text passwords in production systems.
  • Encoding is one-way, verification compares hashed values.

Common mistakes

  • Thinking encoding is reversible like encryption.
  • Using weak encoders like MD5PasswordEncoder in production.

Sample answer

PasswordEncoder is Spring Security's interface for securely hashing and verifying passwords. It provides encode() to hash passwords during registration and matches() to verify passwords during login. The key principle is that passwords are never stored in plain text.

BCryptPasswordEncoder is the recommended implementation because it includes salt generation and is computationally expensive, making brute force attacks impractical. I configure BCrypt with a strength of 12 for our applications, which provides good security while maintaining reasonable performance. The encoding process is one-way, so even if our database is compromised, actual passwords remain protected.

How to level up

  • Use DelegatingPasswordEncoder to support multiple encoding formats during migrations.
  • Tune BCrypt strength based on your security requirements and performance constraints.
  • Consider Argon2PasswordEncoder for even stronger security in high-security applications.

Follow-up questions to expect

  • How would you migrate from an old password encoding scheme to BCrypt?
  • What BCrypt strength would you choose and why?
  • How does password encoding integrate with your user registration flow?
Practice this question with AI feedback →
What is CSRF (Cross-Site Request Forgery) and how does Spring Security protect against it?
easy

What they're really asking

This tests understanding of web security vulnerabilities and whether you know how Spring Security's built-in protections work by default.

How you'll be scored

Weak

Basic definition of CSRF without understanding how Spring Security implements protection or when to disable it.

Average

Correctly explains CSRF attacks and knows about CSRF tokens with basic configuration knowledge.

Strong

Demonstrates understanding of when CSRF protection is needed, how to configure it for different scenarios, and trade-offs with stateless APIs.

How to structure your answer

  1. Define CSRF attack.
  2. Explain Spring Security's token-based protection.
  3. Discuss when protection is enabled.
  4. Cover configuration options.
  5. Address API vs web app considerations.

Key points to hit

  • CSRF attacks trick users into executing unwanted actions on authenticated sites.
  • Spring Security generates and validates CSRF tokens automatically.
  • Protection is enabled by default for state-changing operations.
  • Stateless REST APIs typically disable CSRF protection.

Common mistakes

  • Disabling CSRF protection without understanding the security implications.
  • Not understanding that CSRF protection requires session state.

Sample answer

CSRF is an attack where malicious sites trick authenticated users into performing unwanted actions on other sites they're logged into. Spring Security protects against this by generating unique CSRF tokens that must be included with state-changing requests like POST, PUT, or DELETE. The framework automatically adds tokens to forms and validates them on submission.

For traditional web applications, I keep CSRF protection enabled, but for stateless REST APIs consumed by mobile apps, I disable it since there's no session state and APIs use different authentication mechanisms like JWT tokens.

How to level up

  • Configure custom CSRF token repositories for distributed applications.
  • Use @EnableWebSecurity with csrf().csrfTokenRepository() for custom token handling.
  • Implement proper CSRF token inclusion in AJAX requests with meta tags.

Follow-up questions to expect

  • How would you handle CSRF tokens in AJAX requests?
  • When would you disable CSRF protection and what are the risks?
  • How does CSRF protection work with REST APIs and JWT tokens?
Practice this question with AI feedback →

Spring Security (Intermediate) (14)

What is the Spring Security Filter Chain and how does it work?
medium

What they're really asking

This tests deep understanding of Spring Security's architecture and whether you can troubleshoot authentication and authorization issues by understanding the request processing flow.

How you'll be scored

Weak

Vague understanding of filters without knowledge of specific filter purposes or ordering.

Average

Knows it's a chain of security filters with understanding of some key filters like authentication and authorization.

Strong

Can explain filter ordering, how filters interact, and how to customize the chain for specific security requirements.

How to structure your answer

  1. Explain the filter chain concept.
  2. Describe key filters and their order.
  3. Show how requests flow through filters.
  4. Discuss customization options.
  5. Cover debugging and troubleshooting.

Key points to hit

  • Security filter chain intercepts every request before reaching controllers.
  • Filters execute in specific order: authentication before authorization.
  • Key filters include UsernamePasswordAuthenticationFilter, BasicAuthenticationFilter, and FilterSecurityInterceptor.
  • Chain is customizable through HttpSecurity configuration.

Common mistakes

  • Not understanding filter execution order matters.
  • Assuming all requests go through all filters.

Sample answer

The Spring Security Filter Chain is a series of filters that intercept HTTP requests to handle authentication and authorization before they reach your controllers.

Requests flow through filters in a specific order, starting with security context setup, then authentication filters like UsernamePasswordAuthenticationFilter for form login or BasicAuthenticationFilter for HTTP Basic auth, followed by authorization checks in FilterSecurityInterceptor. Each filter can pass the request to the next filter, redirect for authentication, or deny access.

I customize the chain using HttpSecurity configuration to add custom filters, configure authentication methods, and define URL-specific security rules.

How to level up

  • Use Spring Security's debug logging to trace request flow through filters.
  • Add custom filters with addFilterBefore() or addFilterAfter() for specific security requirements.
  • Understand how SecurityContextPersistenceFilter maintains security context across requests.

Follow-up questions to expect

  • How would you add a custom filter to validate API keys?
  • What happens when an authentication filter fails?
  • How do you debug issues in the security filter chain?
Practice this question with AI feedback →
What is the SecurityContextHolder and SecurityContext?
medium

What they're really asking

This tests understanding of how Spring Security maintains authentication state across requests and whether you know how to access security information programmatically.

How you'll be scored

Weak

Basic knowledge that it stores security info without understanding thread-local storage or context management.

Average

Correctly explains authentication storage with understanding of how to access current user information.

Strong

Demonstrates understanding of thread-local storage, context clearing, and how this integrates with different authentication strategies.

How to structure your answer

  1. Define SecurityContextHolder and SecurityContext.
  2. Explain thread-local storage mechanism.
  3. Show how to access current authentication.
  4. Discuss context management.
  5. Cover integration with different auth strategies.

Key points to hit

  • SecurityContextHolder stores security information using thread-local storage.
  • SecurityContext contains the current Authentication object.
  • Information persists across requests in web applications through session storage.
  • Access current user with SecurityContextHolder.getContext().getAuthentication()

Common mistakes

  • Accessing SecurityContext in async threads without proper context propagation.
  • Not understanding that context is cleared after request processing.

Sample answer

SecurityContextHolder is Spring Security's mechanism for storing the current user's authentication information using thread-local storage. It contains a SecurityContext object, which holds the Authentication object with user details, authorities, and credentials. When a user authenticates, Spring Security populates this context, and it remains available throughout the request processing.

I regularly use SecurityContextHolder.getContext().getAuthentication() to get the current user in my service classes. The context is automatically cleared after each request, but in web applications, it's restored from the session on subsequent requests through the SecurityContextPersistenceFilter.

How to level up

  • Configure SecurityContextHolder strategy for async processing with MODE_INHERITABLETHREADLOCAL.
  • Use @AuthenticationPrincipal annotation in controllers to inject current user directly.
  • Implement custom SecurityContext management for background tasks or scheduled jobs.

Follow-up questions to expect

  • How do you access the current user in an async method?
  • What happens to SecurityContext in a multi-threaded environment?
  • How would you manually set authentication context for testing?
Practice this question with AI feedback →
What is the AuthenticationManager and ProviderManager?
medium

What they're really asking

The interviewer wants to see if you understand the core authentication architecture in Spring Security and how authentication requests flow through the provider chain.

How you'll be scored

Weak

Cannot explain how authentication works internally or confuses authentication with authorization.

Average

Knows AuthenticationManager is involved in authentication but cannot explain ProviderManager or the provider chain pattern.

Strong

Explains the AuthenticationManager interface, ProviderManager as its primary implementation, the chain of AuthenticationProviders, and how authentication tokens flow through the system.

How to structure your answer

  1. Define AuthenticationManager as the core authentication interface.
  2. Explain ProviderManager as its primary implementation.
  3. Describe the AuthenticationProvider chain pattern.
  4. Show how an authentication request flows through the system.

Key points to hit

  • AuthenticationManager is the interface with a single authenticate(Authentication) method that processes authentication requests.
  • ProviderManager is the default implementation that delegates to a chain of AuthenticationProvider instances.
  • Each AuthenticationProvider handles a specific authentication type, like DaoAuthenticationProvider for username/password or JwtAuthenticationProvider for JWT tokens.
  • ProviderManager iterates through providers until one successfully authenticates or all reject, then throws AuthenticationException.

Common mistakes

  • Confusing AuthenticationManager with AuthenticationProvider when the manager delegates to providers.
  • Not understanding that ProviderManager supports a parent AuthenticationManager for fallback authentication.

Sample answer

AuthenticationManager is the central interface in Spring Security's authentication architecture. It has one method, authenticate(), that takes an Authentication object and returns a fully populated Authentication if successful. ProviderManager is the default implementation of AuthenticationManager. What makes it powerful is the chain-of-responsibility pattern.

It holds a list of AuthenticationProvider instances and delegates to each one in order. DaoAuthenticationProvider handles username and password authentication by loading user details from a UserDetailsService. If I add JWT support, I register a JwtAuthenticationProvider that handles bearer tokens.

When a request comes in, ProviderManager asks each provider "can you handle this type of authentication?" The first provider that supports the token type processes it. If authentication succeeds, it returns a fully populated Authentication with authorities. If all providers reject, it throws an AuthenticationException.

How to level up

  • Mention that ProviderManager can have a parent AuthenticationManager, which is useful in applications with multiple SecurityFilterChain configurations.
  • Discuss the ProviderNotFoundException thrown when no provider supports the given authentication token type.
  • Explain how to register custom AuthenticationProviders using AuthenticationManagerBuilder in your security configuration.

Follow-up questions to expect

  • How do you register a custom AuthenticationProvider?
  • What is the Authentication object and what information does it carry?
  • How does DaoAuthenticationProvider validate passwords?
Practice this question with AI feedback →
What is the difference between hasRole and hasAuthority?
medium

What they're really asking

The interviewer wants to see if you understand Spring Security's role and authority model and can avoid the common "ROLE_" prefix confusion that catches many developers.

How you'll be scored

Weak

Thinks they are completely different concepts or does not know either one.

Average

Knows they are related to authorization but cannot explain the ROLE_ prefix convention.

Strong

Explains that hasRole automatically prepends ROLE_ while hasAuthority matches the exact string, and knows when to use each for clean authorization design.

How to structure your answer

  1. Explain that both are used for authorization checks.
  2. Detail the ROLE_ prefix difference.
  3. Show examples of each in practice.
  4. Recommend when to use one over the other.

Key points to hit

  • hasRole("ADMIN") automatically prepends "ROLE_" and checks for the authority "ROLE_ADMIN" in the granted authorities.
  • hasAuthority("ROLE_ADMIN") checks for the exact string "ROLE_ADMIN" without any prefix manipulation.
  • This means hasRole("ADMIN") and hasAuthority("ROLE_ADMIN") are functionally equivalent.
  • Use hasRole for role-based checks (which is the convention) and hasAuthority for fine-grained permissions like "READ_REPORTS" or "DELETE_USERS"

Common mistakes

  • Writing hasRole("ROLE_ADMIN") which results in checking for "ROLE_ROLE_ADMIN" because hasRole adds the prefix automatically.
  • Mixing hasRole and hasAuthority inconsistently across the application, creating confusion about whether authorities have the ROLE_ prefix.

Sample answer

The key difference is the ROLE_ prefix convention. hasRole("ADMIN") automatically prepends "ROLE_" and checks for the authority "ROLE_ADMIN". hasAuthority("ROLE_ADMIN") checks for the exact string without any manipulation. So hasRole("ADMIN") and hasAuthority("ROLE_ADMIN") are equivalent. The common mistake is writing hasRole("ROLE_ADMIN"), which ends up looking for "ROLE_ROLE_ADMIN" and always fails.

In my projects, I use hasRole for coarse-grained role checks like hasRole("ADMIN") or hasRole("USER"). For fine-grained permissions like "CREATE_ORDER" or "DELETE_REPORT", I use hasAuthority because these are not roles and should not have the ROLE_ prefix. This gives me a clean separation between broad roles and specific permissions in my authorization model.

How to level up

  • Mention that the ROLE_ prefix default can be changed by configuring a custom GrantedAuthorityDefaults bean.
  • Discuss how to combine role-based and permission-based authorization using @PreAuthorize with SpEL expressions.
  • Explain how to implement hierarchical roles where ADMIN inherits all USER permissions using RoleHierarchy.

Follow-up questions to expect

  • How do you configure role hierarchy in Spring Security?
  • Can you change the default ROLE_ prefix?
  • How do you implement fine-grained permissions alongside roles?
Practice this question with AI feedback →
What are @PreAuthorize and @PostAuthorize annotations?
medium

What they're really asking

The interviewer wants to see if you understand method-level security and can use SpEL expressions for flexible authorization rules beyond simple role checks.

How you'll be scored

Weak

Has not used method-level security or confuses it with URL-based security.

Average

Knows @PreAuthorize checks before method execution but does not understand @PostAuthorize or SpEL expression capabilities.

Strong

Explains both annotations with SpEL examples, understands the timing difference (before vs after execution), and knows when @PostAuthorize is useful for filtering by return value.

How to structure your answer

  1. Define @PreAuthorize as a pre-execution authorization check.
  2. Define @PostAuthorize as a post-execution authorization check.
  3. Show SpEL expression examples for each.
  4. Explain how to enable method security.

Key points to hit

  • @PreAuthorize evaluates a SpEL expression before the method executes, and blocks access if it returns false.
  • @PostAuthorize evaluates after the method executes and can access the return value through the returnObject variable.
  • Both support SpEL expressions like hasRole(), hasAuthority(), #paramName for method parameters, and authentication.principal for the current user.
  • Method security must be enabled with @EnableMethodSecurity on a configuration class.

Common mistakes

  • Using @PostAuthorize for expensive operations when @PreAuthorize would prevent the unnecessary execution entirely.
  • Forgetting to add @EnableMethodSecurity to activate these annotations, which silently does nothing without it.

Sample answer

@PreAuthorize evaluates a SpEL expression before a method runs. If the expression returns false, Spring throws an AccessDeniedException without executing the method. For example, @PreAuthorize("hasRole('ADMIN') or #userId == authentication.principal.id") checks if the user is an admin or is accessing their own data. @PostAuthorize evaluates after the method executes and has access to the returnObject.

I use @PostAuthorize("returnObject.owner == authentication.name") to ensure users can only see resources they own. The method runs, and if the check fails, the result is discarded and access is denied. Both require @EnableMethodSecurity on your security configuration class. I prefer @PreAuthorize for most cases because it prevents unnecessary work.

I use @PostAuthorize when the authorization decision depends on the actual data returned, which you do not know until after execution.

How to level up

  • Mention @PreFilter and @PostFilter for filtering collections before and after method execution.
  • Discuss creating custom security expressions by extending SecurityExpressionRoot for reusable authorization logic.
  • Explain how to use @PreAuthorize with custom permission evaluators for complex domain-specific authorization.

Follow-up questions to expect

  • How do you create a custom security expression for @PreAuthorize?
  • What is the difference between @PreFilter and @PostFilter?
  • How does @PreAuthorize interact with caching?
Practice this question with AI feedback →
What is the difference between @PreAuthorize and @Secured?
medium

What they're really asking

The interviewer wants to see if you know the evolution of method-level security in Spring and can choose the right annotation for your authorization needs.

How you'll be scored

Weak

Does not know one or both annotations.

Average

Knows both exist but cannot articulate the capabilities difference.

Strong

Explains that @Secured is limited to role checks while @PreAuthorize supports full SpEL expressions, and knows which to use in different scenarios.

How to structure your answer

  1. Define @Secured and its limitations.
  2. Define @PreAuthorize and its SpEL capabilities.
  3. Compare the two directly.
  4. Recommend which to use in modern applications.

Key points to hit

  • @Secured is a simple annotation that only checks for roles or authorities by name, with no expression language support.
  • @PreAuthorize supports Spring Expression Language (SpEL) for complex conditions including role checks, method parameters, and custom expressions.
  • @Secured("ROLE_ADMIN") is equivalent to @PreAuthorize("hasRole('ADMIN')") but @PreAuthorize can do much more.
  • @PreAuthorize is the recommended choice in modern Spring Security because it is more flexible and is part of @EnableMethodSecurity.

Common mistakes

  • Using @Secured when you need complex authorization conditions that require SpEL expressions.
  • Not knowing that @EnableMethodSecurity in Spring Security 6+ enables @PreAuthorize by default but requires explicit securedEnabled = true for @Secured.

Sample answer

@Secured is the older, simpler annotation that only accepts an array of role or authority names. @Secured("ROLE_ADMIN") checks if the user has that exact authority. It cannot combine conditions, access method parameters, or use any expressions. @PreAuthorize is the modern replacement that accepts SpEL expressions.

I can write @PreAuthorize("hasRole('ADMIN') and #id == authentication.principal.id") to combine a role check with a parameter check. I can also call custom methods like @PreAuthorize("@securityService.canAccess(#resourceId)"). In modern Spring Security, I always use @PreAuthorize because it covers everything @Secured does plus much more.

With @EnableMethodSecurity in Spring Security 6, @PreAuthorize is enabled by default, while @Secured requires explicitly setting securedEnabled = true.

How to level up

  • Mention that @Secured does not support SpEL, which means no AND/OR conditions, no parameter access, and no custom method calls.
  • Discuss the migration path from @Secured to @PreAuthorize when upgrading legacy applications.
  • Explain that JSR-250 @RolesAllowed is another alternative that is standardized but equally limited compared to @PreAuthorize.

Follow-up questions to expect

  • How do you enable @Secured in Spring Security 6?
  • Can you use multiple authorization annotations on the same method?
  • How do you test methods protected by @PreAuthorize?
Practice this question with AI feedback →
What is the difference between @Secured and @RolesAllowed?
medium

What they're really asking

The interviewer is testing whether you understand the JSR-250 standard versus Spring-specific annotations and can choose the right one for your project context.

How you'll be scored

Weak

Does not know either annotation or confuses them with other security annotations.

Average

Knows both exist but cannot explain the specification origin or practical differences.

Strong

Explains that @RolesAllowed is the JSR-250 standard and @Secured is Spring-specific, and discusses the portability implications and minor behavioral differences.

How to structure your answer

  1. Define @Secured as a Spring Security annotation.
  2. Define @RolesAllowed as the JSR-250 standard annotation.
  3. Compare their behavior and portability.
  4. Recommend when to use each.

Key points to hit

  • @Secured is Spring Security specific and defined in the org.springframework.security.access.annotation package.
  • @RolesAllowed is a Java EE/Jakarta EE standard annotation from JSR-250, defined in javax.annotation.security (or jakarta.annotation.security)
  • Both have the same basic capability: accepting an array of role names for authorization checks without SpEL support.
  • @RolesAllowed is portable across Java EE containers, while @Secured only works in Spring Security applications.

Common mistakes

  • Thinking there is a major functional difference when both annotations behave nearly identically for role-based authorization.
  • Not enabling jsr250Enabled = true in @EnableMethodSecurity, which is required for @RolesAllowed to work in Spring Security.

Sample answer

The functional difference is minimal, but the origin is different. @Secured is Spring Security's own annotation for method-level authorization. @RolesAllowed comes from JSR-250, which is the Java EE standard for common annotations. Both accept an array of role or authority strings and neither supports SpEL expressions. The practical difference is portability.

If you are building a library that might be used outside Spring Security, @RolesAllowed makes it container-agnostic. In Spring Security 6, both require explicit enabling in @EnableMethodSecurity: securedEnabled = true for @Secured and jsr250Enabled = true for @RolesAllowed. In my projects, I rarely use either one because @PreAuthorize gives me SpEL expressions for complex conditions.

But if I need the simplest possible role check and I want standard Java annotations, I use @RolesAllowed.

How to level up

  • Mention that @RolesAllowed is recognized by Java EE application servers like WildFly and GlassFish without Spring Security.
  • Discuss that both annotations are essentially equivalent in Spring Security and the choice is about coding standards and team conventions.
  • Explain that @PreAuthorize is almost always the better choice in Spring applications because it subsumes the capabilities of both.

Follow-up questions to expect

  • Why would you choose @RolesAllowed over @PreAuthorize?
  • How do you enable JSR-250 annotations in Spring Security 6?
  • Can you use @Secured and @RolesAllowed on the same method?
Practice this question with AI feedback →
What is method-level security and why do you need it?
medium

What they're really asking

This tests your understanding of fine-grained security controls beyond URL-based authorization. The interviewer wants to see if you can secure business logic at the service layer and understand when method-level security is necessary.

How you'll be scored

Weak

Only mentions @PreAuthorize without understanding why you'd use it over URL security.

Average

Explains method-level annotations but doesn't discuss the architectural benefits or trade-offs.

Strong

Demonstrates understanding of defense-in-depth, performance implications, and when method-level security prevents business logic vulnerabilities.

How to structure your answer

  1. Define method-level security and its core annotations.
  2. Explain why URL-level security isn't always sufficient.
  3. Show a concrete example with @PreAuthorize or @Secured.
  4. Discuss performance and architectural considerations.

Key points to hit

  • Method-level security provides defense-in-depth beyond URL filtering.
  • @PreAuthorize, @PostAuthorize, and @Secured annotations secure individual methods.
  • Essential when multiple URLs call the same service method with different security contexts.
  • Requires @EnableGlobalMethodSecurity and can impact performance if overused.

Common mistakes

  • Thinking URL-level security is sufficient for all authorization needs.
  • Not understanding that method security evaluates on every invocation, including internal calls.

Sample answer

Method-level security lets you secure individual methods using annotations like @PreAuthorize, going beyond URL-based filtering. You need it when the same service method is called from different endpoints with different security requirements. For example, a getUserData method might be called from both a public profile endpoint and an admin dashboard, requiring different permissions.

I'd use @PreAuthorize('hasRole("ADMIN") or #userId == authentication.name') to ensure users can only access their own data unless they're admins. This creates defense-in-depth because even if someone bypasses URL security, the business logic is still protected.

How to level up

  • Use SpEL expressions in @PreAuthorize for complex authorization logic that considers method parameters.
  • Consider @PostAuthorize for filtering return values based on user permissions.
  • Cache security evaluations for frequently called methods to avoid performance bottlenecks.

Follow-up questions to expect

  • How would you test methods secured with @PreAuthorize?
  • What's the difference between @PreAuthorize and @Secured?
  • How do you handle method-level security with asynchronous method calls?
Practice this question with AI feedback →
What is OAuth2 and how does Spring Security implement it?
medium

What they're really asking

This tests your knowledge of modern authentication standards and Spring Security's OAuth2 implementation. The interviewer wants to see if you understand OAuth2 flows and can implement secure API access patterns.

How you'll be scored

Weak

Confuses OAuth2 with authentication or can't explain the basic authorization flow.

Average

Knows OAuth2 is for authorization and mentions Spring Security support but lacks implementation details.

Strong

Explains OAuth2 flows, demonstrates understanding of resource servers vs authorization servers, and discusses Spring Security's OAuth2 client and resource server capabilities.

How to structure your answer

  1. Define OAuth2 as an authorization framework and its core purpose.
  2. Explain the key OAuth2 roles and flows.
  3. Show how Spring Security implements OAuth2 client and resource server.
  4. Discuss security considerations and token management.

Key points to hit

  • OAuth2 is an authorization framework for secure API access, not authentication.
  • Involves authorization server, resource server, client, and resource owner roles.
  • Spring Security provides OAuth2 client for consuming APIs and resource server for protecting APIs.
  • Common flows include authorization code, client credentials, and resource owner password.

Common mistakes

  • Confusing OAuth2 with authentication when it's purely authorization.
  • Not understanding the difference between OAuth2 client and resource server configurations.

Sample answer

OAuth2 is an authorization framework that lets applications access APIs on behalf of users without sharing passwords. The key players are the authorization server that issues tokens, resource server that protects APIs, client application, and resource owner. Spring Security implements this through spring-boot-starter-oauth2-client for consuming third-party APIs and spring-boot-starter-oauth2-resource-server for protecting your APIs.

For example, I'd configure OAuth2 login with @EnableOAuth2Sso and set up GitHub as a provider in application.yml. The authorization code flow redirects users to GitHub, exchanges the code for a token, and uses that token to access protected resources.

How to level up

  • Use PKCE (Proof Key for Code Exchange) for public clients to prevent authorization code interception.
  • Implement token relay patterns when your OAuth2 client needs to call downstream services.
  • Configure proper token validation with JWK Set URI for stateless resource server validation.

Follow-up questions to expect

  • How would you implement OAuth2 logout with token revocation?
  • What's the difference between OAuth2 and OpenID Connect?
  • How do you handle OAuth2 token refresh in Spring Security?
Practice this question with AI feedback →
What is JWT (JSON Web Token) and how is it used with Spring Security?
medium

What they're really asking

This tests your understanding of stateless authentication and Spring Security's JWT integration. The interviewer wants to see if you can implement token-based security and understand JWT's benefits and risks.

How you'll be scored

Weak

Knows JWT is a token format but can't explain its structure or security implications.

Average

Understands JWT structure and basic Spring Security integration but misses security concerns.

Strong

Explains JWT structure, demonstrates proper validation configuration, and discusses security considerations like token expiration and secret management.

How to structure your answer

  1. Define JWT structure and its self-contained nature.
  2. Explain JWT's benefits for stateless authentication.
  3. Show Spring Security JWT configuration and validation.
  4. Address security concerns and best practices.

Key points to hit

  • JWT is a self-contained token with header, payload, and signature for stateless authentication.
  • Contains claims that eliminate server-side session storage.
  • Spring Security validates JWTs through JwtDecoder and converts them to Authentication objects.
  • Must be properly validated, have expiration times, and use secure signing algorithms.

Common mistakes

  • Storing sensitive data in JWT payload since it's only base64 encoded, not encrypted.
  • Not implementing proper token expiration and refresh strategies.

Sample answer

JWT is a self-contained token with three parts: header specifying the algorithm, payload containing claims like user ID and roles, and signature for verification. It enables stateless authentication because all user information is in the token itself. In Spring Security, I configure JWT validation using spring-security-oauth2-resource-server dependency and set the JWK Set URI in application.yml.

Spring automatically validates the signature, expiration, and issuer, then converts valid JWTs into Authentication objects. The key benefit is scalability since you don't need server-side sessions, but you must handle token expiration properly and never store sensitive data in the payload since it's just base64 encoded.

How to level up

  • Implement short-lived access tokens with refresh token rotation for better security.
  • Use custom JWT converters to map claims to Spring Security authorities.
  • Consider JWE (encrypted JWTs) when you need to include sensitive information in tokens.

Follow-up questions to expect

  • How do you handle JWT token revocation in a stateless system?
  • What's the difference between symmetric and asymmetric JWT signing?
  • How would you implement JWT refresh token logic?
Practice this question with AI feedback →
How do you handle session management in Spring Security?
medium

What they're really asking

This tests your understanding of session lifecycle management and security considerations. The interviewer wants to see if you can configure session behavior, handle concurrent sessions, and understand the security implications of session management.

How you'll be scored

Weak

Only knows basic session timeout configuration without understanding security implications.

Average

Understands session configuration options but doesn't discuss concurrent sessions or security hardening.

Strong

Demonstrates knowledge of session fixation protection, concurrent session control, session clustering for scalability, and proper session invalidation.

How to structure your answer

  1. Explain Spring Security's default session management behavior.
  2. Show configuration options for session timeout and concurrent sessions.
  3. Discuss session security features like fixation protection.
  4. Address scalability concerns with session clustering or stateless alternatives.

Key points to hit

  • Spring Security provides session fixation protection and concurrent session control by default.
  • Configure session timeout, maximum concurrent sessions, and invalid session handling.
  • Session clustering or external session stores enable horizontal scaling.
  • Consider stateless alternatives like JWT for microservices architectures.

Common mistakes

  • Not configuring session fixation protection, leaving applications vulnerable to session hijacking.
  • Ignoring concurrent session limits, allowing unlimited sessions per user.

Sample answer

Spring Security manages sessions through HttpSessionSecurityContextRepository and provides session fixation protection by default, creating a new session ID after authentication. I configure session management in SecurityConfig using sessionManagement(), setting session timeout in application.properties with server.servlet.session.timeout. For concurrent sessions, I use maximumSessions(1) to limit users to one active session and sessionRegistry to track active sessions.

In production, I use Spring Session with Redis to share sessions across multiple application instances, enabling horizontal scaling. For APIs, I often prefer stateless authentication with JWT to avoid session management complexity entirely.

How to level up

  • Implement custom InvalidSessionStrategy to handle expired sessions gracefully with proper redirects.
  • Use SessionRegistry to programmatically expire user sessions when needed, like after password changes.
  • Configure secure session cookies with HttpOnly and Secure flags, and consider SameSite attributes for CSRF protection.

Follow-up questions to expect

  • How would you implement session clustering across multiple servers?
  • What's the difference between session fixation and session hijacking?
  • How do you handle session management in a microservices architecture?
Practice this question with AI feedback →
How do you configure role-based access control (RBAC)?
medium

What they're really asking

This tests your ability to implement hierarchical access control and understand Spring Security's role-based authorization mechanisms. The interviewer wants to see if you can design flexible permission systems and handle complex authorization scenarios.

How you'll be scored

Weak

Only mentions roles without understanding authorities or how to implement flexible role hierarchies.

Average

Understands basic role configuration but doesn't discuss role hierarchies or dynamic role assignment.

Strong

Demonstrates role hierarchies, custom UserDetailsService implementation, method-level role checking, and database-driven role management.

How to structure your answer

  1. Explain the difference between roles and authorities in Spring Security.
  2. Show role hierarchy configuration for inherited permissions.
  3. Demonstrate database-driven role assignment with custom UserDetailsService.
  4. Address dynamic role changes and caching considerations.

Key points to hit

  • Roles are authorities with ROLE_ prefix, enabling hierarchical permission inheritance.
  • Configure role hierarchies so ADMIN inherits USER permissions automatically.
  • Implement custom UserDetailsService to load roles from database dynamically.
  • Use @PreAuthorize with role expressions for fine-grained method-level control.

Common mistakes

  • Hardcoding roles in configuration instead of loading them dynamically from database.
  • Not implementing role hierarchies, leading to complex permission checking logic.

Sample answer

RBAC in Spring Security uses roles as authorities with a ROLE_ prefix and supports hierarchical inheritance. I configure role hierarchies in SecurityConfig so ROLE_ADMIN automatically includes ROLE_USER permissions, eliminating duplicate permission checks. I implement a custom UserDetailsService that loads user roles from the database, converting them to GrantedAuthority objects.

For URL protection, I use hasRole('ADMIN') in HttpSecurity configuration, and for method-level security, I use @PreAuthorize('hasRole("MANAGER") or hasRole("ADMIN")'). To handle role changes without requiring logout, I integrate with Spring Security's session registry to expire sessions when user roles change, forcing fresh authentication with updated permissions.

How to level up

  • Implement role caching with cache eviction strategies to handle dynamic role changes efficiently.
  • Use granted authorities voter for complex permission logic that goes beyond simple role checking.
  • Consider separating functional roles from data access roles for more flexible permission models.

Follow-up questions to expect

  • How would you implement dynamic role assignment without requiring user logout?
  • What's the difference between hasRole() and hasAuthority() in Spring Security?
  • How do you handle role-based access control in a multi-tenant application?
Practice this question with AI feedback →
What is DelegatingFilterProxy?
medium

What they're really asking

The interviewer wants to see if you understand the bridge between the servlet container's filter mechanism and Spring's application context, which is foundational to how Spring Security integrates with web applications.

How you'll be scored

Weak

Has no idea what DelegatingFilterProxy is or how servlet filters relate to Spring.

Average

Knows it is a servlet filter but cannot explain the delegation mechanism or why it is necessary.

Strong

Explains the bridge pattern between the servlet container and Spring's ApplicationContext, the lazy initialization benefit, and how it connects to FilterChainProxy in Spring Security.

How to structure your answer

  1. Explain the problem: servlet filters are managed by the container, not Spring.
  2. Define DelegatingFilterProxy as the bridge between the two worlds.
  3. Show how it delegates to a Spring-managed bean.
  4. Connect it to Spring Security's FilterChainProxy.

Key points to hit

  • DelegatingFilterProxy is a servlet filter registered with the servlet container that delegates to a Spring-managed bean implementing the Filter interface.
  • It solves the problem that servlet filters are created by the web container before the Spring ApplicationContext is available.
  • In Spring Security, DelegatingFilterProxy delegates to FilterChainProxy, which is the Spring-managed bean named "springSecurityFilterChain"
  • Spring Boot auto-registers DelegatingFilterProxy, so you rarely configure it manually, but understanding it explains how the security filter chain integrates with the servlet lifecycle.

Common mistakes

  • Not understanding that DelegatingFilterProxy is a servlet container filter, not a Spring bean, and that its job is to bridge the two worlds.
  • Confusing DelegatingFilterProxy with FilterChainProxy when they serve different purposes in the chain.

Sample answer

DelegatingFilterProxy solves a specific integration problem. Servlet filters are created and managed by the servlet container like Tomcat, while Spring beans live in the ApplicationContext.

DelegatingFilterProxy is a standard servlet filter that the container creates, but instead of containing filter logic itself, it looks up a Spring bean by name and delegates all filter calls to it. In Spring Security, this Spring bean is the FilterChainProxy, registered as "springSecurityFilterChain".

So the request flow is: Tomcat calls DelegatingFilterProxy, which delegates to FilterChainProxy, which then runs through the chain of Spring Security filters like UsernamePasswordAuthenticationFilter and AuthorizationFilter. Spring Boot auto-registers this for you, so you never manually configure it.

But understanding it is important because it explains why Spring Security can use dependency injection and the full power of the ApplicationContext in its filter chain.

How to level up

  • Mention that DelegatingFilterProxy supports lazy initialization, delaying the Spring bean lookup until the first request.
  • Discuss how FilterChainProxy can manage multiple SecurityFilterChain instances for different URL patterns.
  • Explain that in Spring Boot, SecurityFilterAutoConfiguration handles the automatic registration of DelegatingFilterProxy.

Follow-up questions to expect

  • What is FilterChainProxy and how does it relate to DelegatingFilterProxy?
  • How many security filter chains can you have in a single application?
  • What is the order of filters in Spring Security's filter chain?
Practice this question with AI feedback →
How do you secure RESTful APIs with Spring Security?
medium

What they're really asking

The interviewer wants to see if you can configure Spring Security for stateless API security, which is fundamentally different from traditional session-based web security.

How you'll be scored

Weak

Only knows about basic authentication or form login without understanding stateless API security.

Average

Mentions JWT or OAuth2 but cannot explain the full configuration needed for stateless REST API security.

Strong

Demonstrates a complete security configuration including stateless session management, token-based authentication, CSRF considerations, and endpoint-level authorization.

How to structure your answer

  1. Explain why REST API security differs from web application security.
  2. Show the SecurityFilterChain configuration for stateless APIs.
  3. Detail the authentication mechanism (JWT, OAuth2)
  4. Discuss endpoint-level authorization rules.

Key points to hit

  • REST APIs should use stateless session management with http.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
  • CSRF protection can typically be disabled for stateless APIs because they do not use cookies for authentication.
  • JWT tokens or OAuth2 bearer tokens are the standard authentication mechanisms, validated by a custom filter or Spring's resource server support.
  • Endpoint authorization is configured with requestMatchers() to allow public endpoints and secure others based on roles or permissions.

Common mistakes

  • Using form login configuration for REST APIs when token-based authentication is the standard approach.
  • Disabling CSRF without switching to stateless session management, which leaves the API vulnerable if sessions are still used.

Sample answer

Securing REST APIs with Spring Security is different from web apps because APIs are stateless. In my SecurityFilterChain bean, I start by setting session management to STATELESS so Spring Security never creates HTTP sessions. I disable CSRF because stateless APIs use tokens instead of cookies, which are what CSRF protects.

For authentication, I use spring-boot-starter-oauth2-resource-server which gives me JWT validation out of the box. I configure http.oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults())) and set the issuer URI in application.properties. For endpoint authorization, I use http.authorizeHttpRequests(auth -> auth.requestMatchers("/api/public/**").permitAll().requestMatchers("/api/admin/**").hasRole("ADMIN").anyRequest().authenticated()). I also add a @RestControllerAdvice to return proper 401 and 403 JSON responses instead of HTML login pages.

This gives me a clean, stateless API security setup.

How to level up

  • Discuss implementing a custom JwtAuthenticationConverter to map JWT claims to Spring Security authorities.
  • Mention API key authentication as an alternative to JWT for service-to-service communication.
  • Explain how to combine multiple authentication mechanisms in the same application using multiple SecurityFilterChain beans with @Order.

Follow-up questions to expect

  • How do you implement JWT authentication without using OAuth2 resource server?
  • When should you keep CSRF enabled for an API?
  • How do you handle refresh tokens in a stateless API?
Practice this question with AI feedback →

Ready to put this into practice?

Try these questions in a mock interview →

Still applying for jobs? Let Auto Apply do it

Spring Security (Advanced) (10)

How do you implement a custom AuthenticationProvider?
hard

What they're really asking

The interviewer wants to see if you can extend Spring Security's authentication mechanism for custom authentication sources like LDAP, external APIs, or multi-factor flows.

How you'll be scored

Weak

Cannot explain the AuthenticationProvider interface or when you would need a custom one.

Average

Understands you implement the interface but misses the supports() method, error handling, or registration process.

Strong

Demonstrates the full implementation including authenticate(), supports(), proper exception handling, password encoding, and registration with the AuthenticationManager.

How to structure your answer

  1. Explain when you need a custom AuthenticationProvider.
  2. Show the interface methods: authenticate() and supports()
  3. Detail the implementation with proper error handling.
  4. Show how to register it with Spring Security.

Key points to hit

  • Implement the AuthenticationProvider interface with authenticate(Authentication) and supports(Class) methods.
  • The supports() method determines which Authentication token types this provider handles, typically UsernamePasswordAuthenticationToken.
  • authenticate() validates credentials and returns a fully populated Authentication object with authorities on success, or throws AuthenticationException on failure.
  • Register the provider in your SecurityFilterChain configuration using AuthenticationManagerBuilder or by exposing it as a bean.

Common mistakes

  • Returning null from authenticate() when authentication fails instead of throwing AuthenticationException, which causes silent failures.
  • Forgetting to implement supports() correctly, which means the ProviderManager never delegates to your provider.

Sample answer

I create a custom AuthenticationProvider when the built-in DaoAuthenticationProvider does not fit my authentication source. I implement the AuthenticationProvider interface with two methods. First, supports() returns true for UsernamePasswordAuthenticationToken.class or whatever token type I am handling.

Second, authenticate() receives the Authentication object, extracts the credentials, validates them against my custom source, and returns a new UsernamePasswordAuthenticationToken with the authenticated principal, null credentials, and a list of GrantedAuthority objects. If validation fails, I throw a BadCredentialsException. In one project, I built a custom provider that authenticated against an external REST API.

I called the API with the username and password, and if it returned a valid user profile, I created the authentication token with the appropriate roles. I register the provider as a @Component bean, and Spring Security's auto-configuration picks it up automatically through the AuthenticationManagerBuilder.

How to level up

  • Mention that you can chain multiple AuthenticationProviders, each handling different authentication mechanisms.
  • Discuss how to use the AuthenticationEventPublisher to emit events on authentication success and failure for audit logging.
  • Explain the importance of erasing credentials from the Authentication object after successful authentication for security.

Follow-up questions to expect

  • How do you handle authentication against multiple sources in order of priority?
  • What events does Spring Security publish during authentication?
  • How do you test a custom AuthenticationProvider?
Practice this question with AI feedback →
How do you implement token revocation in OAuth2 with Spring Security?
hard

What they're really asking

The interviewer wants to see if you understand the challenge of invalidating stateless JWT tokens and can implement practical revocation strategies for production systems.

How you'll be scored

Weak

Does not understand why token revocation is difficult with JWTs or has no strategy for it.

Average

Mentions a token blacklist but does not discuss the implementation details, storage, or performance implications.

Strong

Explains multiple revocation strategies, their trade-offs, and demonstrates a concrete implementation with Spring Security including short-lived tokens with refresh token rotation.

How to structure your answer

  1. Explain why token revocation is challenging with stateless JWTs.
  2. List revocation strategies and their trade-offs.
  3. Show a practical implementation approach.
  4. Discuss production considerations.

Key points to hit

  • JWTs are stateless and self-contained, meaning the server cannot inherently invalidate them before expiration without introducing state.
  • Token blacklist/denylist stores revoked token IDs (JTI claims) in a fast store like Redis, checked on every request.
  • Short-lived access tokens combined with refresh token rotation minimize the window of vulnerability and allow revocation at the refresh step.
  • Spring Security's resource server can be customized with a JwtDecoder that checks the blacklist or with a custom OpaqueTokenIntrospector for opaque tokens that are always validated server-side.

Common mistakes

  • Ignoring token revocation entirely and relying solely on token expiration, which leaves a vulnerability window for stolen tokens.
  • Implementing a blacklist in a local in-memory store instead of a shared store like Redis, which breaks in distributed deployments.

Sample answer

Token revocation is inherently challenging with JWTs because they are stateless. Once issued, the server has no way to invalidate them without introducing some state. My preferred approach is combining short-lived access tokens (5 to 15 minutes) with refresh token rotation. The access token has a short life, limiting exposure if stolen.

When it expires, the client uses the refresh token to get a new access token. I store refresh tokens in Redis and can revoke them immediately by deleting them. For cases where I need immediate access token revocation, I maintain a JWT denylist in Redis.

I store the JTI (JWT ID) claim of revoked tokens with a TTL matching the token's remaining lifetime. In my Spring Security configuration, I create a custom JwtDecoder wrapper that checks the Redis denylist before validating the JWT. If the JTI is in the denylist, it throws an InvalidBearerTokenException.

This adds one Redis lookup per request, which is sub-millisecond.

How to level up

  • Discuss opaque tokens as an alternative where every request is validated against the authorization server, making revocation trivial but adding latency.
  • Mention the token introspection endpoint (RFC 7662) for delegating revocation checks to the authorization server.
  • Explain how token families and refresh token rotation detect token theft by invalidating the entire family when a reused refresh token is detected.

Follow-up questions to expect

  • What are the trade-offs between JWT and opaque tokens for revocation?
  • How do you implement refresh token rotation?
  • How do you handle token revocation across multiple microservices?
Practice this question with AI feedback →
How do you implement two-factor authentication in Spring Security?
hard

What they're really asking

The interviewer wants to see if you can extend Spring Security's authentication flow for multi-step authentication, which tests your understanding of the authentication architecture and custom filter implementation.

How you'll be scored

Weak

Has no idea how to add a second authentication factor to Spring Security.

Average

Understands the concept but cannot explain how to integrate it into Spring Security's authentication flow.

Strong

Demonstrates a concrete implementation strategy with custom authentication tokens, a multi-step authentication flow, and TOTP or SMS verification integration.

How to structure your answer

  1. Explain the 2FA concept and common second factors.
  2. Design the multi-step authentication flow.
  3. Detail the Spring Security integration points.
  4. Discuss TOTP implementation specifics.

Key points to hit

  • Two-factor authentication requires something you know (password) and something you have (TOTP app, SMS code) for stronger security.
  • Implement a custom AuthenticationProvider that first validates username and password, then returns a partially authenticated token that requires a second factor.
  • Create a custom Authentication token class like TwoFactorAuthenticationToken with states for primary authentication and fully authenticated.
  • Use a TOTP library like Google Authenticator or WakaTime to generate and validate time-based one-time passwords.

Common mistakes

  • Fully authenticating after the first factor and then checking the second factor as a separate authorization step, which creates a window where single-factor access is possible.
  • Storing TOTP secrets in plain text instead of encrypting them in the database.

Sample answer

I implement 2FA by creating a multi-step authentication flow within Spring Security. First, I create a custom TwoFactorAuthenticationToken that extends AbstractAuthenticationToken and has a state field for PRIMARY_AUTHENTICATED and FULLY_AUTHENTICATED. My custom AuthenticationProvider validates the username and password, and if 2FA is enabled for the user, returns a TwoFactorAuthenticationToken with PRIMARY_AUTHENTICATED status and limited authorities.

The client then presents a second endpoint with the TOTP code. A second filter or controller validates the TOTP code using a library that implements RFC 6238, checking it against the user's encrypted secret stored in the database. On success, I create a new TwoFactorAuthenticationToken with FULLY_AUTHENTICATED status and full authorities.

I use spring-security-totp or java-totp for the TOTP implementation, which handles time window validation and code generation. The QR code for the authenticator app setup is generated using the secret key and encoded as an otpauth:// URI.

How to level up

  • Discuss implementing backup recovery codes that are single-use and stored as hashed values for users who lose their authenticator device.
  • Mention remember-me functionality for trusted devices that bypasses 2FA for a configured period.
  • Explain how to handle 2FA enrollment flow where new users set up their authenticator app with a QR code during first login.

Follow-up questions to expect

  • How do you handle the case where a user loses their authenticator device?
  • What is the difference between TOTP and HOTP?
  • How do you implement remember-this-device functionality for 2FA?
Practice this question with AI feedback →
What are the implications of stateless session management for REST APIs?
hard

What they're really asking

This tests your understanding of REST API security architecture and how stateless design affects authentication, authorization, and session handling in production microservices.

How you'll be scored

Weak

Only mentions JWT tokens without understanding the security implications or alternatives.

Average

Explains stateless authentication with JWT but misses scalability benefits and security considerations.

Strong

Demonstrates deep understanding of stateless trade-offs, token security, and how it enables horizontal scaling.

How to structure your answer

  1. Define stateless session management in REST context.
  2. Explain authentication mechanisms (JWT, OAuth2)
  3. Discuss authorization and token validation.
  4. Address security considerations and token lifecycle.
  5. Compare with stateful alternatives and when to use each.

Key points to hit

  • Stateless means no server-side session storage, enabling horizontal scaling and load balancer flexibility.
  • JWT tokens carry authentication and authorization claims, eliminating database lookups per request.
  • Token expiration and refresh strategies prevent long-lived security risks.
  • HTTPS is mandatory since tokens travel with every request.

Common mistakes

  • Storing sensitive data in JWT payload without encryption.
  • Not implementing proper token expiration and refresh mechanisms.

Sample answer

Stateless session management means the server doesn't store any session information, which is crucial for REST APIs because it enables horizontal scaling and simplifies load balancing. I typically use JWT tokens that contain authentication and authorization claims, so each request is self-contained.

The client sends the token in the Authorization header, and Spring Security validates it without hitting a database. The main security implications are that tokens must have short expiration times, we need a refresh token strategy, and HTTPS becomes mandatory since credentials travel with every request.

This approach scales much better than stateful sessions but requires careful token lifecycle management.

How to level up

  • Implement token blacklisting for immediate revocation despite stateless design.
  • Use asymmetric keys (RS256) instead of symmetric (HS256) for JWT signing in distributed systems.
  • Consider implementing sliding window expiration for better user experience.

Follow-up questions to expect

  • How would you handle token revocation in a stateless system?
  • What's your strategy for JWT key rotation in production?
  • How do you balance token expiration time with user experience?
Practice this question with AI feedback →
How do you secure a microservices architecture using Spring Security?
hard

What they're really asking

This tests your ability to design security architecture across distributed services, handling service-to-service authentication, API gateway patterns, and shared security contexts.

How you'll be scored

Weak

Suggests applying monolithic security patterns without understanding microservices challenges.

Average

Mentions API gateway and JWT but lacks depth on service-to-service communication security.

Strong

Demonstrates comprehensive understanding of distributed security including service mesh, mutual TLS, and token propagation.

How to structure your answer

  1. Identify microservices security challenges (service-to-service auth, distributed context)
  2. Explain API gateway as security perimeter.
  3. Discuss service-to-service authentication strategies.
  4. Address token propagation and context sharing.
  5. Cover monitoring and security audit across services.

Key points to hit

  • API gateway acts as single entry point for external authentication and authorization.
  • Service-to-service communication requires mutual TLS or service tokens.
  • Security context propagation ensures consistent user identity across service calls.
  • OAuth2 Resource Server configuration enables token validation at each service boundary.

Common mistakes

  • Implementing authentication at every service instead of centralizing at API gateway.
  • Not securing internal service-to-service communication assuming private network safety.

Sample answer

In microservices, I implement security in layers starting with an API gateway that handles external authentication using OAuth2 or JWT. The gateway validates tokens and forwards them to downstream services configured as OAuth2 resource servers using @EnableResourceServer.

For service-to-service calls, I use either mutual TLS certificates or service-specific JWT tokens with Spring Security's OAuth2RestTemplate to propagate security context. Each service validates incoming tokens locally using shared public keys, avoiding central auth service bottlenecks. I also implement security headers propagation using Spring Cloud Sleuth to maintain audit trails across the entire request flow.

How to level up

  • Implement circuit breakers for authentication services to prevent cascading security failures.
  • Use Spring Cloud Gateway filters for consistent security policy enforcement.
  • Consider service mesh solutions like Istio for transparent mTLS between services.

Follow-up questions to expect

  • How do you handle authentication service failures in a microservices architecture?
  • What's your approach to managing certificates for mutual TLS at scale?
  • How do you implement fine-grained authorization across multiple services?
Practice this question with AI feedback →
How do you configure Spring Security for a multi-tenant application?
hard

What they're really asking

This tests your ability to design security systems that isolate tenants while sharing infrastructure, including data separation, authentication routing, and configuration management.

How you'll be scored

Weak

Confuses multi-tenancy with simple user roles or doesn't understand tenant isolation requirements.

Average

Explains basic tenant identification but misses security isolation and data separation concerns.

Strong

Demonstrates comprehensive understanding of tenant isolation, security boundaries, and scalable multi-tenant architecture.

How to structure your answer

  1. Define multi-tenancy and security isolation requirements.
  2. Explain tenant identification and routing strategies.
  3. Discuss data separation and access control per tenant.
  4. Address configuration and customization per tenant.
  5. Cover monitoring and audit trail separation.

Key points to hit

  • Tenant identification through subdomain, header, or JWT claims determines security context.
  • Data isolation requires tenant-aware repositories and query filters at the ORM level.
  • Separate security configurations per tenant enable different authentication providers.
  • @TenantId annotation or similar ensures automatic tenant filtering in data access.

Common mistakes

  • Relying only on application-level tenant filtering without database-level constraints.
  • Not properly isolating tenant data in shared database schemas.

Sample answer

For multi-tenant applications, I start by implementing tenant identification through JWT claims or request headers, then use Spring Security's authentication managers to route to tenant-specific authentication providers. I create a TenantContext that stores the current tenant ID in ThreadLocal and use @PreFilter annotations to automatically add tenant constraints to database queries.

For data isolation, I implement tenant-aware JPA repositories with @Where clauses and use separate DataSource configurations when tenants require database isolation. Security configurations are externalized per tenant using @ConfigurationProperties with tenant-specific property files, allowing different OAuth2 providers or password policies per tenant.

How to level up

  • Implement tenant-aware caching strategies to prevent cross-tenant data leakage.
  • Use custom SecurityContextRepository to handle tenant-specific security contexts.
  • Consider using Spring Boot's @ConditionalOnProperty for tenant-specific bean configuration.

Follow-up questions to expect

  • How do you prevent accidental cross-tenant data access in your repositories?
  • What's your strategy for tenant-specific feature flags and configurations?
  • How do you handle tenant onboarding and security setup automation?
Practice this question with AI feedback →
How do you secure WebSocket connections with Spring Security?
hard

What they're really asking

This tests your understanding of WebSocket security challenges including authentication, authorization, CSRF protection, and maintaining security context during persistent connections.

How you'll be scored

Weak

Doesn't understand that WebSocket connections bypass normal HTTP security or suggests inappropriate solutions.

Average

Mentions WebSocket security configuration but lacks depth on connection lifecycle and authorization.

Strong

Demonstrates comprehensive understanding of WebSocket security challenges and appropriate Spring Security integration patterns.

How to structure your answer

  1. Identify WebSocket security challenges (persistent connections, bypassing HTTP filters)
  2. Explain WebSocket authentication during handshake.
  3. Discuss message-level authorization and subscription security.
  4. Address CSRF and origin validation.
  5. Cover connection lifecycle and session management.

Key points to hit

  • WebSocket authentication occurs during HTTP handshake upgrade using standard Spring Security.
  • Message-level security requires @MessageMapping methods with @PreAuthorize annotations.
  • STOMP over WebSocket enables subscription-based authorization with custom interceptors.
  • Origin validation and CSRF tokens prevent unauthorized WebSocket connections.

Common mistakes

  • Not validating message-level authorization assuming connection-level auth is sufficient.
  • Ignoring CSRF protection for WebSocket endpoints.

Sample answer

WebSocket security in Spring requires configuration at both connection and message levels. I secure the initial handshake using standard HTTP security with @EnableWebSocketSecurity, which authenticates users during the upgrade request. For message-level security, I use @PreAuthorize on @MessageMapping methods and implement custom ChannelInterceptor to validate user permissions for STOMP destinations.

I also configure StompHeaderAccessor to extract authentication from messages and use AbstractSecurityWebSocketMessageBrokerConfigurer to apply security policies to message channels. CSRF protection is handled by validating tokens during handshake and implementing proper origin checking to prevent cross-site WebSocket hijacking.

How to level up

  • Implement custom AuthenticationPrincipalArgumentResolver for extracting user context in WebSocket handlers.
  • Use SimpMessagingTemplate with user-specific destinations for secure message delivery.
  • Consider implementing connection throttling and rate limiting for WebSocket endpoints.

Follow-up questions to expect

  • How do you handle user authorization changes during active WebSocket sessions?
  • What's your approach to scaling WebSocket security across multiple server instances?
  • How do you implement message-level encryption for sensitive WebSocket communications?
Practice this question with AI feedback →
How do you implement custom security annotations?
hard

What they're really asking

This tests your ability to extend Spring Security's authorization system by creating domain-specific security annotations and understanding the underlying AOP and method security mechanisms.

How you'll be scored

Weak

Suggests basic @PreAuthorize usage without understanding how to create truly custom annotations.

Average

Shows how to create custom annotations but lacks understanding of the underlying security evaluation context.

Strong

Demonstrates deep understanding of Spring Security's method security infrastructure and can create reusable, type-safe security abstractions.

How to structure your answer

  1. Explain the need for custom security annotations beyond built-in options.
  2. Show how to create custom annotation with @PreAuthorize or @PostAuthorize.
  3. Demonstrate custom PermissionEvaluator implementation.
  4. Explain integration with method security infrastructure.
  5. Address testing and debugging custom security annotations.

Key points to hit

  • Custom annotations combine @PreAuthorize with domain-specific SpEL expressions for reusability.
  • PermissionEvaluator interface enables object-level security with hasPermission() SpEL function.
  • @EnableGlobalMethodSecurity with prePostEnabled=true activates custom annotation processing.
  • Custom SecurityExpressionRoot provides domain-specific functions for SpEL expressions.

Common mistakes

  • Creating annotations that don't properly integrate with Spring's security context.
  • Not considering performance implications of complex authorization logic in annotations.

Sample answer

I create custom security annotations by combining @PreAuthorize with domain-specific logic for better reusability and readability. For example, I'd create @RequireOwnership annotation that uses @PreAuthorize with hasPermission() SpEL function, then implement PermissionEvaluator to check if the current user owns the specified resource.

I register the evaluator using @EnableGlobalMethodSecurity and implement the evaluation logic to query ownership relationships. For complex domain logic, I extend SecurityExpressionRoot to add custom SpEL functions like isManager() or canAccessProject(). This approach keeps security logic centralized, makes it unit testable, and provides type-safe security constraints that are self-documenting in the codebase.

How to level up

  • Implement caching in PermissionEvaluator to avoid repeated authorization queries.
  • Use @Retention(RUNTIME) and document annotation parameters for better IDE support.
  • Create annotation composition with multiple security concerns combined into single annotation.

Follow-up questions to expect

  • How do you test methods secured with your custom annotations?
  • What's your strategy for handling performance of complex authorization logic?
  • How do you debug issues with custom security annotations in production?
Practice this question with AI feedback →
What is Spring Security ACL (Access Control List) and how do you implement fine-grained access control?
hard

What they're really asking

This tests advanced Spring Security knowledge and ability to implement domain-level authorization. The interviewer wants to see if you can design secure systems with object-level permissions beyond role-based access.

How you'll be scored

Weak

Cannot explain what ACL is or confuses it with basic role-based security.

Average

Knows ACL provides object-level permissions but struggles with implementation details.

Strong

Demonstrates understanding of ACL architecture, can implement custom permissions, and discusses performance implications.

How to structure your answer

  1. Define ACL and explain object-level vs role-level security.
  2. Describe ACL components: ACL service, permissions, and SID.
  3. Show configuration setup and database schema.
  4. Provide implementation example with @PreAuthorize.
  5. Discuss performance considerations and alternatives.

Key points to hit

  • ACL provides fine-grained, instance-level authorization beyond roles using object identity and permissions.
  • Requires ACL tables storing object identities, access control entries, and security identities.
  • Uses @PreAuthorize with hasPermission() expressions to check object-specific access rights.
  • Performance overhead requires caching strategy and careful query optimization for production use.

Common mistakes

  • Confusing ACL with basic role-based security or method-level security.
  • Not understanding the database schema requirements and performance implications of ACL queries.

Sample answer

Spring Security ACL provides object-level authorization where you can grant specific permissions like READ or WRITE to individual domain objects, not just roles. It uses four database tables to store object identities, access control entries, and security identities.

For example, I can configure ACL so user John has READ access to Document ID 123 but not Document ID 124. I'd implement this by configuring AclService with a JdbcMutableAclService, then use @PreAuthorize('hasPermission(#documentId, 'Document', 'READ')') on my service methods.

The main trade-off is performance since every permission check requires database queries, so proper caching with EhCache is essential for production systems.

How to level up

  • Implement custom Permission classes for domain-specific permissions beyond standard READ/WRITE/DELETE.
  • Use batch loading strategies to reduce N+1 query problems when checking permissions on collections.
  • Consider implementing custom AclService with Redis caching for high-performance scenarios.

Follow-up questions to expect

  • How would you handle ACL performance in a system with millions of objects?
  • Can you show how to programmatically create ACL entries when new objects are created?
  • What are the alternatives to Spring Security ACL for fine-grained authorization?
Practice this question with AI feedback →
How do you use Spring Security in a reactive programming model (WebFlux)?
hard

What they're really asking

This tests knowledge of reactive security patterns and WebFlux integration. The interviewer wants to see if you understand non-blocking security in reactive streams and can configure authentication/authorization for reactive applications.

How you'll be scored

Weak

Cannot explain reactive security concepts or tries to apply traditional Spring MVC security patterns to WebFlux.

Average

Understands basic reactive security setup but lacks depth on authentication flows and context propagation.

Strong

Demonstrates understanding of ReactiveSecurityContextHolder, WebFilter chains, and can implement custom reactive authentication.

How to structure your answer

  1. Explain reactive security fundamentals and context propagation.
  2. Show WebFlux security configuration with ServerHttpSecurity.
  3. Demonstrate authentication with ReactiveAuthenticationManager.
  4. Explain authorization using @PreAuthorize in reactive controllers.
  5. Address context propagation across reactive chains.

Key points to hit

  • Uses ServerHttpSecurity instead of HttpSecurity for configuring WebFlux security chains.
  • ReactiveSecurityContextHolder provides non-blocking access to security context in reactive streams.
  • Authentication returns Mono<Authentication> and integrates with reactive WebFilter chains.
  • Context propagation requires careful handling to maintain security context across async operations.

Common mistakes

  • Trying to use traditional HttpSecurity configuration with WebFlux applications.
  • Not understanding how security context propagates through reactive operators like flatMap and map.

Sample answer

In WebFlux, Spring Security operates on reactive streams using ServerHttpSecurity instead of HttpSecurity. The key difference is everything returns Mono or Flux types for non-blocking operations. I configure security by extending ReactiveSecurityConfigurerAdapter and using ServerHttpSecurity to set up authentication managers that return Mono<Authentication>.

For accessing the current user in reactive controllers, I use ReactiveSecurityContextHolder.getContext().map() to extract authentication non-blockingly. The tricky part is context propagation, where security context must be explicitly passed through reactive chains using contextWrite() operators to maintain authentication across async operations.

How to level up

  • Implement custom ReactiveAuthenticationManager for JWT token validation that integrates with external identity providers.
  • Use @AuthenticationPrincipal in reactive controller methods to automatically inject authenticated user into Mono parameters.
  • Configure custom ServerAccessDeniedHandler and ServerAuthenticationEntryPoint for proper error handling in reactive flows.

Follow-up questions to expect

  • How do you handle JWT token validation in a reactive authentication flow?
  • What happens to security context when using parallel processing in WebFlux?
  • Can you show how to implement custom reactive authorization rules for method-level security?
Practice this question with AI feedback →

Spring Microservices (Beginner) (4)

What is a microservice and how is it different from a monolith?
easy

What they're really asking

This tests fundamental architectural understanding and ability to articulate trade-offs between different system designs. The interviewer wants to see if you understand when to choose microservices over monoliths.

How you'll be scored

Weak

Gives vague definition without understanding trade-offs or when to use each approach.

Average

Correctly defines both but lacks depth on practical implications and decision criteria.

Strong

Demonstrates clear understanding of trade-offs, can explain when each is appropriate, and mentions operational complexity.

How to structure your answer

  1. Define microservices as independently deployable services around business capabilities.
  2. Contrast with monolith as single deployable unit with shared database.
  3. Explain key differences in deployment, scaling, and team structure.
  4. Discuss trade-offs: complexity vs scalability.
  5. Provide guidance on when to choose each approach.

Key points to hit

  • Microservices are independently deployable services with separate databases and business boundaries.
  • Monoliths deploy as single unit with shared database and simpler operational overhead.
  • Microservices enable independent scaling and team autonomy but increase operational complexity.
  • Choose microservices when you have organizational scale and clear service boundaries, otherwise start with monolith.

Common mistakes

  • Thinking microservices are always better or that monoliths are legacy architecture.
  • Not understanding the operational complexity and distributed system challenges that come with microservices.

Sample answer

A microservice is an independently deployable service that owns its data and represents a specific business capability, like user management or order processing. Each service has its own database and can be developed by separate teams. A monolith packages everything into a single deployable unit with a shared database.

The key trade-off is complexity versus scalability. Microservices let you scale individual components and use different technologies per service, but they introduce network latency, distributed system failures, and operational overhead.

I typically recommend starting with a well-structured monolith and extracting microservices only when you have clear service boundaries and the team size to manage the operational complexity.

How to level up

  • Focus on business capabilities and data ownership boundaries rather than technical concerns when designing service boundaries.
  • Consider the two-pizza team rule: if you can't manage the operational complexity with small teams, stick with monolith.
  • Understand that microservices are an organizational pattern as much as a technical one, requiring DevOps maturity.

Follow-up questions to expect

  • How do you identify the right boundaries for splitting a monolith into microservices?
  • What are the main challenges you face when moving from monolith to microservices?
  • How do you handle data consistency across multiple microservices?
Practice this question with AI feedback →
What is Spring Cloud?
easy

What they're really asking

This tests basic knowledge of Spring's cloud-native ecosystem and understanding of distributed system patterns. The interviewer wants to see if you know the main Spring Cloud components and their purposes.

How you'll be scored

Weak

Cannot name key Spring Cloud components or their purposes in distributed systems.

Average

Names some components like Config Server or Gateway but lacks understanding of how they work together.

Strong

Demonstrates understanding of Spring Cloud ecosystem, can explain multiple components, and knows when to use them.

How to structure your answer

  1. Define Spring Cloud as toolkit for distributed system patterns.
  2. List key components: Config, Gateway, Discovery, Circuit Breaker.
  3. Explain how components work together in microservices architecture.
  4. Give concrete example of Spring Cloud in action.
  5. Mention integration with cloud platforms.

Key points to hit

  • Spring Cloud provides patterns for distributed systems like configuration management, service discovery, and circuit breakers.
  • Key components include Config Server for externalized configuration, Gateway for API routing, and Eureka for service registry.
  • Circuit Breaker pattern with Hystrix or Resilience4j prevents cascade failures in distributed systems.
  • Integrates with cloud platforms like AWS, Azure, and GCP for cloud-native development.

Common mistakes

  • Confusing Spring Cloud with Spring Boot or not understanding it's specifically for distributed systems.
  • Not knowing the main components or their specific purposes in microservices architecture.

Sample answer

Spring Cloud is a toolkit that provides common patterns for building distributed systems and microservices. It includes components like Spring Cloud Config for managing application properties across environments, Spring Cloud Gateway for API routing and filtering, and service discovery with Eureka or Consul.

For example, in a typical setup, my microservices register with Eureka discovery server, pull configuration from Config Server, and route external requests through Gateway which handles load balancing and security. It also includes circuit breaker patterns with Resilience4j to prevent cascade failures when services are down.

The main benefit is it handles the operational complexity of distributed systems so I can focus on business logic.

How to level up

  • Understand the difference between Spring Cloud Netflix (older) and Spring Cloud LoadBalancer/Gateway (current recommended approach)
  • Learn how Spring Cloud Config integrates with Git repositories for versioned configuration management.
  • Know that Spring Cloud provides cloud platform integrations beyond just the core distributed system patterns.

Follow-up questions to expect

  • How do you handle configuration changes in Spring Cloud Config without restarting services?
  • What's the difference between Spring Cloud Gateway and Netflix Zuul?
  • How do you implement distributed tracing across Spring Cloud microservices?
Practice this question with AI feedback →
How do microservices communicate with each other?
easy

What they're really asking

This tests understanding of distributed system communication patterns and ability to choose appropriate integration strategies. The interviewer wants to see if you know both synchronous and asynchronous communication options.

How you'll be scored

Weak

Only knows HTTP REST calls without understanding trade-offs or alternative communication patterns.

Average

Knows REST and messaging but lacks depth on when to use each pattern.

Strong

Demonstrates understanding of multiple communication patterns, their trade-offs, and can choose appropriate strategy for different scenarios.

How to structure your answer

  1. Categorize communication as synchronous vs asynchronous.
  2. Explain HTTP REST for synchronous request-response.
  3. Describe messaging for asynchronous, event-driven communication.
  4. Discuss service discovery for finding service endpoints.
  5. Address error handling and resilience patterns.

Key points to hit

  • Synchronous communication uses HTTP REST with direct service-to-service calls for immediate responses.
  • Asynchronous communication uses message queues like RabbitMQ or Kafka for event-driven, decoupled interactions.
  • Service discovery mechanisms like Eureka help services find each other without hardcoded URLs.
  • Circuit breaker patterns prevent cascade failures and timeouts handle network issues in distributed calls.

Common mistakes

  • Only thinking about HTTP REST without considering asynchronous messaging for decoupled communication.
  • Not understanding the importance of service discovery and resilience patterns in microservice communication.

Sample answer

Microservices communicate through two main patterns: synchronous and asynchronous. For synchronous communication, I use HTTP REST calls with tools like RestTemplate or WebClient, along with service discovery through Eureka so services can find each other without hardcoded URLs.

For asynchronous communication, I use message queues like RabbitMQ or event streaming with Kafka, which decouples services and handles high throughput better. The choice depends on the use case: REST for immediate responses like user queries, messaging for events like order processing that don't need immediate response.

I always add circuit breakers and timeouts to handle network failures gracefully and prevent cascade failures across the system.

How to level up

  • Understand event sourcing and CQRS patterns for complex data consistency requirements across services.
  • Learn about API composition patterns and backends-for-frontends when aggregating data from multiple services.
  • Consider gRPC for high-performance service-to-service communication when you control both ends.

Follow-up questions to expect

  • How do you handle distributed transactions across multiple microservices?
  • What's your strategy for API versioning when services need to evolve independently?
  • How do you implement request tracing across multiple service calls for debugging?
Practice this question with AI feedback →
What is service discovery and why do we need it?
easy

What they're really asking

This tests microservices architecture understanding and whether you grasp the dynamic nature of distributed systems. The interviewer wants to see if you understand why hardcoded service locations don't work at scale.

How you'll be scored

Weak

Gives a vague definition without explaining the dynamic discovery aspect or why it matters in microservices.

Average

Correctly explains service discovery as finding services dynamically but lacks concrete examples or implementation details.

Strong

Demonstrates understanding of service registry patterns, explains the problems it solves, and mentions specific tools like Eureka or Consul.

How to structure your answer

  1. Define what service discovery is.
  2. Explain the problem it solves in microservices.
  3. Describe how it works with a service registry.
  4. Give concrete examples of tools.
  5. Mention production benefits.

Key points to hit

  • Service discovery eliminates hardcoded service locations in distributed systems.
  • Service registry acts as a phone book for microservices.
  • Enables dynamic scaling and deployment without configuration changes.
  • Tools like Eureka, Consul, or Kubernetes service discovery handle this automatically.

Common mistakes

  • Confusing service discovery with load balancing.
  • Not explaining why hardcoded URLs break in microservices.

Sample answer

Service discovery is how microservices find and communicate with each other without hardcoded URLs. In a microservice architecture, services are constantly starting, stopping, and moving between servers, so you can't just put static IPs in your configuration.

Instead, services register themselves with a service registry like Eureka when they start up, and other services query the registry to find available instances. For example, when my order service needs to call the payment service, it asks Eureka for all healthy payment service instances and gets back current IP addresses and ports.

How to level up

  • Discuss health checks and how unhealthy services are automatically removed from discovery.
  • Mention client-side vs server-side discovery patterns and their trade-offs.
  • Explain how service discovery integrates with load balancing for fault tolerance.

Follow-up questions to expect

  • How do you handle service discovery in a containerized environment like Kubernetes?
  • What happens if the service registry itself goes down?
  • How do you implement health checks for service discovery?
Practice this question with AI feedback →

Ready to put this into practice?

Try these questions in a mock interview →

Still applying for jobs? Let Auto Apply do it

Spring Microservices (Intermediate) (9)

What is an API Gateway and why is it important?
medium

What they're really asking

This tests distributed systems architecture knowledge and whether you understand the complexity that arises when clients interact with multiple microservices. The interviewer wants to see if you grasp cross-cutting concerns in microservices.

How you'll be scored

Weak

Describes it as just a proxy without understanding the specific problems it solves in microservices architectures.

Average

Correctly identifies it as a single entry point but only mentions basic routing functionality.

Strong

Explains multiple responsibilities like authentication, rate limiting, and protocol translation, with understanding of when to use it.

How to structure your answer

  1. Define API Gateway as a single entry point.
  2. Explain the problems it solves.
  3. List key responsibilities and features.
  4. Discuss benefits for both clients and backend services.
  5. Mention implementation options.

Key points to hit

  • API Gateway provides a single entry point for all client requests to microservices.
  • Handles cross-cutting concerns like authentication, rate limiting, and logging.
  • Enables protocol translation and request/response transformation.
  • Spring Cloud Gateway offers reactive programming model with filters and predicates.

Common mistakes

  • Thinking API Gateway is just for routing without understanding cross-cutting concerns.
  • Not considering the single point of failure risk that gateways introduce.

Sample answer

An API Gateway is a single entry point that sits between clients and your microservices, handling all incoming requests and routing them to appropriate backend services. It's important because it centralizes cross-cutting concerns that would otherwise be duplicated across every microservice.

For instance, instead of implementing authentication in each of my 15 microservices, I handle it once in the gateway. It also handles rate limiting, request logging, and protocol translation, like converting HTTP requests to gRPC calls. Spring Cloud Gateway makes this easy with its filter chains and predicates for routing logic.

How to level up

  • Discuss the Backend for Frontend (BFF) pattern where different gateways serve different client types.
  • Explain how to avoid making the gateway a bottleneck through proper scaling and caching strategies.
  • Mention circuit breaker patterns in gateways to handle downstream service failures.

Follow-up questions to expect

  • How do you prevent the API Gateway from becoming a single point of failure?
  • What's the difference between Spring Cloud Gateway and Zuul?
  • How do you handle versioning of APIs through the gateway?
Practice this question with AI feedback →
Explain the role of Eureka in a Spring Boot microservice architecture.
medium

What they're really asking

This tests specific Spring Cloud Netflix knowledge and whether you understand service registry implementation details. The interviewer wants to see hands-on experience with Eureka configuration and troubleshooting.

How you'll be scored

Weak

Only knows Eureka is for service discovery without understanding its specific architecture or configuration.

Average

Explains Eureka server and client roles but lacks details about registration, heartbeats, or production considerations.

Strong

Demonstrates understanding of Eureka server/client architecture, self-preservation mode, and production deployment patterns.

How to structure your answer

  1. Explain Eureka as Netflix's service registry implementation.
  2. Describe server and client components.
  3. Detail registration and heartbeat process.
  4. Discuss high availability and clustering.
  5. Mention production considerations.

Key points to hit

  • Eureka Server acts as the service registry where microservices register themselves.
  • Eureka Client handles automatic registration and heartbeat maintenance.
  • Self-preservation mode prevents mass de-registration during network partitions.
  • @EnableEurekaServer and @EnableEurekaClient annotations enable functionality.

Common mistakes

  • Not understanding self-preservation mode and why services might appear available when they're not.
  • Forgetting that Eureka favors availability over consistency in CAP theorem.

Sample answer

Eureka is Netflix's service registry implementation that consists of Eureka Server and Eureka Client. The server maintains a registry of all service instances, while clients automatically register themselves using @EnableEurekaClient and send heartbeats every 30 seconds.

What's unique about Eureka is its self-preservation mode, which prevents mass de-registration during network issues by refusing to remove services when renewal rates drop below a threshold. In production, I typically run multiple Eureka servers in different availability zones, and they replicate the registry between themselves to ensure high availability.

How to level up

  • Understand Eureka's eventually consistent model and how it handles network partitions differently than CP systems.
  • Configure proper heartbeat intervals and renewal thresholds based on your network conditions.
  • Use Eureka's metadata features to store custom information like version numbers or deployment environments.

Follow-up questions to expect

  • How do you secure Eureka server endpoints in production?
  • What happens when a Eureka server goes down?
  • How do you handle service discovery in a multi-region deployment?
Practice this question with AI feedback →
How do you handle configuration management across microservices (Spring Cloud Config)?
medium

What they're really asking

This tests distributed configuration management understanding and whether you know how to externalize configuration without rebuilding services. The interviewer wants to see experience with environment-specific deployments and configuration security.

How you'll be scored

Weak

Mentions Spring Cloud Config but doesn't understand the centralized configuration problem it solves.

Average

Explains centralized configuration concept but lacks implementation details or security considerations.

Strong

Demonstrates understanding of config server setup, encryption, refresh mechanisms, and production deployment patterns.

How to structure your answer

  1. Explain the distributed configuration problem.
  2. Describe Spring Cloud Config Server architecture.
  3. Detail client-side integration.
  4. Discuss configuration refresh and profiles.
  5. Address security and encryption.

Key points to hit

  • Spring Cloud Config Server centralizes configuration in Git repositories or other backends.
  • Clients fetch configuration at startup using @EnableConfigClient or bootstrap.yml.
  • Supports environment-specific profiles and property overrides.
  • Provides encryption/decryption for sensitive values and @RefreshScope for runtime updates.

Common mistakes

  • Not understanding that configuration changes require application restart unless using @RefreshScope.
  • Storing sensitive data in plain text instead of using encryption features.

Sample answer

Spring Cloud Config solves the problem of managing configuration across dozens of microservices without rebuilding applications for each environment. I set up a Config Server with @EnableConfigServer that serves configuration from a Git repository, organized by service name and profile like user-service-dev.yml.

Client services use bootstrap.yml to locate the config server and fetch their configuration at startup. For sensitive data like database passwords, I use the encryption features with {cipher} prefixed values, and for runtime updates, I use @RefreshScope on beans that need to pick up new configuration when I POST to the /actuator/refresh endpoint.

How to level up

  • Implement configuration webhooks so services automatically refresh when Git configuration changes.
  • Use Spring Cloud Bus with message brokers to broadcast configuration changes to all instances simultaneously.
  • Consider using HashiCorp Vault backend for more advanced secret management than built-in encryption.

Follow-up questions to expect

  • How do you handle configuration rollbacks when a bad config is deployed?
  • What happens if the Config Server is unavailable when a service starts?
  • How do you audit configuration changes across your microservices?
Practice this question with AI feedback →
How do you achieve load balancing in microservices?
medium

What they're really asking

This tests understanding of fault tolerance and traffic distribution in microservices. The interviewer wants to see knowledge of both client-side and server-side load balancing approaches and their trade-offs.

How you'll be scored

Weak

Only mentions load balancing without understanding client-side vs server-side approaches or Spring-specific implementations.

Average

Explains basic load balancing concepts but lacks details about Spring Cloud LoadBalancer or integration with service discovery.

Strong

Demonstrates understanding of different load balancing strategies, Spring Cloud LoadBalancer, and how it integrates with service discovery.

How to structure your answer

  1. Define load balancing in microservices context.
  2. Explain client-side vs server-side approaches.
  3. Detail Spring Cloud LoadBalancer implementation.
  4. Discuss load balancing algorithms.
  5. Address fault tolerance and health checks.

Key points to hit

  • Client-side load balancing distributes requests at the application level using service discovery.
  • Spring Cloud LoadBalancer replaced Ribbon for client-side load balancing.
  • @LoadBalanced RestTemplate and WebClient automatically distribute requests across instances.
  • Supports multiple algorithms like round-robin, random, and weighted response time.

Common mistakes

  • Confusing load balancing with service discovery when they work together but serve different purposes.
  • Not understanding that client-side load balancing requires service discovery to get the list of available instances.

Sample answer

In microservices, load balancing distributes requests across multiple service instances for better performance and fault tolerance. Spring Cloud LoadBalancer provides client-side load balancing, where each service instance decides which downstream service to call based on the list from service discovery.

I use @LoadBalanced on my RestTemplate or WebClient, and it automatically distributes requests across available instances using algorithms like round-robin. This integrates seamlessly with Eureka, so when instances go down, they're automatically removed from the load balancing pool.

For more control, I can implement custom LoadBalancerClient logic to route based on request headers or other criteria.

How to level up

  • Implement sticky sessions using consistent hashing when services maintain state.
  • Use circuit breakers with load balancing to avoid cascading failures when instances become unhealthy.
  • Consider zone-aware load balancing to prefer instances in the same availability zone for reduced latency.

Follow-up questions to expect

  • How do you handle load balancing when services have different response times?
  • What's the difference between client-side and server-side load balancing?
  • How do you implement health checks that influence load balancing decisions?
Practice this question with AI feedback →
What is circuit breaking and how does it help? (Resilience4j / Hystrix)
medium

What they're really asking

The interviewer wants to see if you understand resilience patterns for distributed systems and can prevent cascading failures when downstream services become unavailable.

How you'll be scored

Weak

Does not understand the circuit breaker pattern or why it is needed in microservices.

Average

Explains the concept but cannot detail the three states or how to implement it with Resilience4j in Spring Boot.

Strong

Explains the three states (closed, open, half-open), demonstrates Resilience4j configuration, and discusses fallback strategies and monitoring.

How to structure your answer

  1. Explain the cascading failure problem in microservices.
  2. Define the circuit breaker pattern with its three states.
  3. Show Resilience4j implementation in Spring Boot.
  4. Discuss fallback strategies and configuration.

Key points to hit

  • Circuit breaking prevents cascading failures by stopping requests to a failing service instead of letting timeouts pile up and exhaust resources.
  • Three states: CLOSED (requests pass through normally), OPEN (requests fail immediately without calling the downstream service), HALF_OPEN (limited requests pass through to test recovery)
  • Resilience4j is the modern replacement for Hystrix (which is in maintenance mode) and integrates with Spring Boot through spring-cloud-starter-circuitbreaker-resilience4j.
  • Configure failure rate thresholds, wait duration in open state, and ring buffer sizes through application properties or @CircuitBreaker annotation.

Common mistakes

  • Using Hystrix for new projects when it has been in maintenance mode since 2018 and Resilience4j is the recommended replacement.
  • Not defining fallback methods, which means the circuit breaker just throws exceptions instead of providing a degraded response.

Sample answer

In a microservices architecture, if Service A calls Service B and Service B goes down, the requests from A pile up waiting for timeouts. If A has a thread pool of 200 threads and they are all blocked waiting for B, A itself becomes unresponsive and the failure cascades to everyone calling A.

Circuit breaking stops this cascade. I use Resilience4j in Spring Boot by adding the spring-cloud-starter-circuitbreaker-resilience4j dependency. I annotate service methods with @CircuitBreaker(name = "inventoryService", fallbackMethod = "inventoryFallback"). The circuit starts CLOSED, passing all requests through.

If the failure rate exceeds my threshold, say 50% over the last 10 calls, it trips to OPEN and immediately returns the fallback response without calling the service. After a configured wait duration, it moves to HALF_OPEN and lets a few test requests through. If they succeed, it closes the circuit.

My fallback methods return cached data, default values, or a graceful degradation response.

How to level up

  • Mention combining circuit breakers with retry, rate limiter, and bulkhead patterns in Resilience4j for comprehensive resilience.
  • Discuss monitoring circuit breaker state through Actuator endpoints and Prometheus metrics.
  • Explain sliding window types: count-based versus time-based, and when each is appropriate.

Follow-up questions to expect

  • How do you monitor circuit breaker state in production?
  • What is the bulkhead pattern and how does it complement circuit breaking?
  • How do you configure different circuit breaker settings for different services?
Practice this question with AI feedback →
What is distributed tracing and how do you implement it? (Zipkin, Sleuth, Micrometer Tracing)
medium

What they're really asking

The interviewer wants to see if you can debug and monitor request flows across multiple microservices, which is essential for troubleshooting production issues in distributed systems.

How you'll be scored

Weak

Does not understand why distributed tracing is needed or confuses it with logging.

Average

Knows about trace IDs and span IDs but cannot explain the implementation or the tooling.

Strong

Explains the concepts of traces and spans, demonstrates Spring Boot integration with Micrometer Tracing, and discusses visualization with Zipkin or Jaeger.

How to structure your answer

  1. Explain why distributed tracing is necessary in microservices.
  2. Define traces and spans.
  3. Show Spring Boot implementation with Micrometer Tracing.
  4. Discuss visualization and analysis tools.

Key points to hit

  • Distributed tracing follows a request across service boundaries by propagating a unique trace ID and creating spans for each service interaction.
  • A trace represents the entire request journey, and spans represent individual operations within that trace.
  • Spring Boot 3 uses Micrometer Tracing (replacing Spring Cloud Sleuth) with bridges to OpenTelemetry or Brave for trace context propagation.
  • Traces are exported to backends like Zipkin, Jaeger, or Grafana Tempo for visualization, latency analysis, and bottleneck detection.

Common mistakes

  • Referencing Spring Cloud Sleuth for new Spring Boot 3 projects when it has been replaced by Micrometer Tracing.
  • Not understanding that trace context must be propagated through HTTP headers, message queues, and async calls for complete traces.

Sample answer

Distributed tracing solves the problem of understanding how a single user request flows through multiple microservices. Without it, debugging a slow response that crosses five services is nearly impossible. I implement it in Spring Boot 3 using Micrometer Tracing, which replaced Spring Cloud Sleuth.

I add the micrometer-tracing-bridge-brave or micrometer-tracing-bridge-otel dependency, along with a reporter like zipkin-reporter-brave. Micrometer Tracing automatically generates a unique trace ID for each incoming request and creates spans for each service call, database query, and message published.

When Service A calls Service B, the trace ID propagates through HTTP headers so both services share the same trace. I export these traces to Zipkin, where I can visualize the full request timeline, see which service added the most latency, and identify the exact point of failure.

The auto-instrumentation also adds the trace ID to log entries through MDC, so I can search logs by trace ID.

How to level up

  • Mention sampling strategies to reduce trace volume in high-throughput production systems, like tracing only 10% of requests.
  • Discuss OpenTelemetry as the industry standard that unifies tracing, metrics, and logging instrumentation.
  • Explain how to add custom spans for business-critical operations using the @NewSpan annotation or Tracer API.

Follow-up questions to expect

  • What is the difference between Micrometer Tracing and Spring Cloud Sleuth?
  • How do you propagate trace context through message queues?
  • How do you balance trace completeness with storage costs in production?
Practice this question with AI feedback →
How do you manage centralized logging across multiple microservices?
medium

What they're really asking

The interviewer wants to see if you have production experience operating microservices and can implement observability practices that make debugging distributed systems practical.

How you'll be scored

Weak

Suggests reading log files on individual servers, which does not scale in a microservices environment.

Average

Mentions the ELK stack or a similar tool but cannot explain the full pipeline from application to searchable logs.

Strong

Describes the complete logging pipeline including structured logging, log aggregation, correlation IDs, and search/alerting capabilities.

How to structure your answer

  1. Explain why centralized logging is necessary in microservices.
  2. Describe the logging pipeline architecture.
  3. Show Spring Boot configuration for structured logging.
  4. Discuss log correlation with trace IDs.

Key points to hit

  • Centralized logging collects logs from all microservice instances into a single searchable system, replacing the need to SSH into individual servers.
  • The standard pipeline is: application logs to stdout, collected by a log shipper (Filebeat, Fluentd), sent to a central store (Elasticsearch, Loki), and queried through a UI (Kibana, Grafana)
  • Structured JSON logging in Spring Boot using logstash-logback-encoder enables machine-parseable log entries with consistent fields.
  • Correlation IDs (trace IDs from Micrometer Tracing) in every log entry allow filtering all logs related to a single request across services.

Common mistakes

  • Logging to files inside containers, which are ephemeral and lost when the container restarts.
  • Not using structured logging format, which makes parsing and searching logs unreliable with unstructured text.

Sample answer

In a microservices architecture with dozens of instances, you cannot SSH into servers to read log files. I implement centralized logging using the ELK pattern. In each Spring Boot service, I configure logstash-logback-encoder to output structured JSON logs to stdout. Each log entry includes fields like service name, trace ID, span ID, and business context.

In Kubernetes, a DaemonSet running Filebeat or Fluentd collects these JSON logs from container stdout and ships them to Elasticsearch. I query logs through Kibana where I can search across all services. The most powerful feature is trace ID correlation.

When a user reports an issue, I search by their trace ID and see every log entry from every service that handled their request, in chronological order. I also set up Kibana alerts for error rate spikes and specific exception patterns to catch issues before users report them.

How to level up

  • Discuss the shift from ELK to Grafana Loki as a more cost-effective solution for log aggregation with native Kubernetes integration.
  • Mention MDC (Mapped Diagnostic Context) for adding custom context like user ID or request path to every log entry automatically.
  • Explain log retention strategies and index lifecycle management to control storage costs.

Follow-up questions to expect

  • How do you handle log volume in high-throughput microservices?
  • What is the difference between ELK stack and Grafana Loki?
  • How do you set up alerts based on log patterns?
Practice this question with AI feedback →
How do microservices share data?
medium

What they're really asking

The interviewer wants to see if you understand the data ownership challenge in microservices and can choose appropriate patterns for inter-service data access.

How you'll be scored

Weak

Suggests sharing a database between microservices, which violates the fundamental microservices principle.

Average

Knows services should have separate databases but only mentions synchronous REST calls as the data sharing mechanism.

Strong

Explains the database-per-service principle and demonstrates multiple data sharing patterns including API calls, events, and CQRS with their appropriate use cases.

How to structure your answer

  1. State the database-per-service principle.
  2. Explain synchronous data sharing (API calls)
  3. Explain asynchronous data sharing (events)
  4. Discuss the CQRS and materialized view pattern.

Key points to hit

  • Each microservice owns its data and exposes it through its API, never through direct database access by other services.
  • Synchronous sharing via REST or gRPC calls is simple but creates runtime coupling and latency.
  • Asynchronous sharing via events (Kafka, RabbitMQ) decouples services and allows each to maintain a local copy of the data it needs.
  • The saga pattern coordinates multi-service data changes without distributed transactions by using a sequence of local transactions with compensating actions.

Common mistakes

  • Sharing a database between services, which creates tight coupling, prevents independent deployment, and makes schema changes risky.
  • Always choosing synchronous REST calls when event-driven patterns would provide better decoupling and resilience.

Sample answer

The fundamental rule is that each microservice owns its data. No two services should share a database. For sharing data, I use three patterns depending on the use case. For real-time lookups, I use synchronous API calls with Spring's WebClient or RestClient. The Order Service calls the Product Service API to get product details.

For decoupled data propagation, I use events. When the User Service updates a profile, it publishes a UserUpdated event to Kafka. Services that need user data consume this event and store a local projection. This way, if the User Service is down, the Order Service still has the user data it needs.

For complex queries spanning multiple services, I use the CQRS pattern where a dedicated query service listens to events from multiple services and builds a denormalized read model. In Spring Boot, I implement this with Spring Cloud Stream for Kafka integration and Spring Data for the local projections.

How to level up

  • Discuss the API composition pattern for aggregating data from multiple services at the gateway level.
  • Mention the challenges of maintaining data consistency across local copies and how to handle stale data.
  • Explain how GraphQL federation can provide a unified data layer across microservices without data duplication.

Follow-up questions to expect

  • How do you handle data consistency when services have their own copies?
  • When would you use synchronous versus asynchronous data sharing?
  • What is the saga pattern and how does it handle failures?
Practice this question with AI feedback →
What is eventual consistency?
medium

What they're really asking

The interviewer wants to see if you understand the CAP theorem trade-offs in distributed systems and can design systems that tolerate temporary inconsistency for better availability.

How you'll be scored

Weak

Does not understand what eventual consistency means or confuses it with strong consistency.

Average

Defines eventual consistency correctly but cannot explain why it is necessary or how to handle it in practice.

Strong

Explains the concept in context of the CAP theorem, gives concrete microservices examples, and discusses strategies for handling the inconsistency window.

How to structure your answer

  1. Define eventual consistency versus strong consistency.
  2. Explain why it is necessary in distributed systems (CAP theorem)
  3. Give practical microservices examples.
  4. Discuss strategies for handling the inconsistency window.

Key points to hit

  • Eventual consistency means that after a data update, all replicas or services will eventually converge to the same state, but there is a window where they may be out of sync.
  • It is a trade-off from the CAP theorem: in a distributed system, you can have consistency and partition tolerance, or availability and partition tolerance, but not all three.
  • Most microservices architectures choose availability and partition tolerance, accepting eventual consistency as the trade-off.
  • Strategies for handling the inconsistency window include idempotent operations, optimistic concurrency control, read-your-own-writes patterns, and compensation mechanisms.

Common mistakes

  • Treating eventual consistency as a bug to fix rather than a design choice that enables scalability and availability.
  • Not communicating the consistency model to frontend developers who need to handle stale reads in the UI.

Sample answer

Eventual consistency means that when you update data in one service, other services will eventually see the change, but not immediately. There is a window where different services have different versions of the truth. In a microservices architecture, this is unavoidable when services own their own data.

For example, when a customer changes their address in the User Service, the Order Service might still show the old address for a few seconds until it processes the AddressChanged event from the message queue. The system is eventually consistent because given enough time and no new updates, all services converge.

I handle this in practice with several strategies. Idempotent event handlers so duplicate messages do not cause problems. Optimistic concurrency with version numbers to detect conflicting updates. Read-your-own-writes by routing reads to the service that just processed the write. And clear UI feedback that tells users their change is being processed.

How to level up

  • Discuss the difference between eventual, strong, and causal consistency models and when each is appropriate.
  • Mention the outbox pattern for reliable event publishing that guarantees at-least-once delivery from database changes to message queues.
  • Explain how event sourcing provides a natural eventual consistency model with full audit trail and replayability.

Follow-up questions to expect

  • How do you detect and resolve conflicts in an eventually consistent system?
  • What is the outbox pattern and why is it important for eventual consistency?
  • When should you prefer strong consistency over eventual consistency?
Practice this question with AI feedback →

Spring Microservices (Advanced) (9)

What is the Saga pattern in microservices?
hard

What they're really asking

This tests your understanding of distributed transaction management in microservices. The interviewer wants to see if you grasp how to maintain data consistency across services without traditional ACID transactions.

How you'll be scored

Weak

Gives a vague definition without understanding the problem it solves or how it differs from traditional transactions.

Average

Explains the basic concept and mentions choreography vs orchestration but lacks concrete implementation details.

Strong

Demonstrates deep understanding of distributed transaction challenges, explains both Saga types with Spring Boot implementation examples, and discusses compensating actions.

How to structure your answer

  1. Define the Saga pattern and the problem it solves.
  2. Explain the two types: choreography and orchestration.
  3. Provide Spring Boot implementation approach.
  4. Discuss compensating transactions and failure handling.
  5. Address when to use Saga vs alternatives.

Key points to hit

  • Saga manages distributed transactions through a sequence of local transactions with compensating actions.
  • Choreography uses events while orchestration uses a central coordinator.
  • Spring State Machine or Axon Framework can implement orchestration-based Sagas.
  • Each step must be reversible through compensating transactions.

Common mistakes

  • Confusing Saga with traditional two-phase commit protocols.
  • Not explaining how compensating actions work in practice.

Sample answer

The Saga pattern solves distributed transaction management in microservices by breaking a business transaction into a sequence of local transactions, each with a compensating action. For example, in an e-commerce order process, we'd have separate transactions for payment, inventory, and shipping services.

If the shipping service fails, we execute compensating actions to refund payment and restore inventory. I've implemented this using Spring State Machine for orchestration, where a central service coordinates the flow, or through event choreography using Spring Cloud Stream where services react to events.

The key is designing idempotent compensating actions that can reliably undo previous steps.

How to level up

  • Discuss implementing Saga with Spring State Machine for complex workflows.
  • Explain how to handle partial failures and ensure idempotency of compensating actions.
  • Address monitoring and observability challenges in Saga implementations.

Follow-up questions to expect

  • How would you implement rollback mechanisms in a Saga?
  • What happens if a compensating action fails?
  • How do you ensure data consistency during the Saga execution?
Practice this question with AI feedback →
What is the difference between orchestration and choreography in microservices?
hard

What they're really asking

This tests your architectural understanding of microservice coordination patterns. The interviewer wants to see if you can choose the right pattern based on complexity and coupling requirements.

How you'll be scored

Weak

Cannot clearly distinguish between the two patterns or explain when to use each.

Average

Correctly explains both patterns but doesn't provide concrete Spring Boot implementation details or trade-offs.

Strong

Clearly explains both patterns with Spring Boot examples, discusses trade-offs like coupling vs complexity, and provides guidance on when to choose each.

How to structure your answer

  1. Define orchestration and choreography patterns.
  2. Explain the role of central coordinator vs event-driven approach.
  3. Show Spring Boot implementation examples for both.
  4. Compare trade-offs: coupling, complexity, and failure handling.
  5. Provide decision criteria for choosing between them.

Key points to hit

  • Orchestration uses a central service to coordinate workflow steps.
  • Choreography relies on services reacting to events without central control.
  • Spring Boot supports orchestration through services and choreography through Spring Cloud Stream.
  • Orchestration offers better visibility but higher coupling, choreography provides loose coupling but complex debugging.

Common mistakes

  • Thinking one pattern is always better than the other without considering context.
  • Not understanding the coupling implications of each approach.

Sample answer

Orchestration uses a central service to control the workflow, like an OrderService that calls PaymentService, then InventoryService, then ShippingService sequentially. I implement this with @RestTemplate or @FeignClient calls. Choreography eliminates the central coordinator, instead, services publish and consume events. When OrderService publishes 'OrderCreated', PaymentService reacts, then publishes 'PaymentProcessed', triggering InventoryService.

I use Spring Cloud Stream with RabbitMQ for this. Orchestration gives better visibility and easier debugging but creates coupling. Choreography provides loose coupling but makes it harder to trace business flows. I choose orchestration for critical, complex workflows and choreography for loosely coupled, event-driven processes.

How to level up

  • Combine both patterns, use orchestration for critical business flows and choreography for notifications and analytics.
  • Implement correlation IDs across all services to trace distributed workflows regardless of pattern.
  • Consider using Spring State Machine for complex orchestration scenarios with branching logic.

Follow-up questions to expect

  • How do you handle timeouts in orchestrated workflows?
  • How do you debug a failed choreographed process?
  • Can you combine both patterns in the same system?
Practice this question with AI feedback →
How do you version APIs in a microservices architecture?
hard

What they're really asking

This tests your API evolution strategy in distributed systems. The interviewer wants to see if you understand backward compatibility, client management, and deployment strategies in microservices.

How you'll be scored

Weak

Only mentions basic versioning approaches like URL versioning without understanding the implications.

Average

Explains multiple versioning strategies but doesn't address client compatibility or migration strategies.

Strong

Demonstrates comprehensive understanding of versioning strategies, backward compatibility requirements, and provides concrete Spring Boot implementation with migration approaches.

How to structure your answer

  1. Explain why API versioning is critical in microservices.
  2. Present different versioning strategies with pros and cons.
  3. Show Spring Boot implementation approaches.
  4. Discuss backward compatibility and deprecation strategies.
  5. Address client migration and monitoring approaches.

Key points to hit

  • Multiple strategies: URL path, header, query parameter, and content negotiation versioning.
  • Spring Boot supports versioning through @RequestMapping variations and custom annotations.
  • Maintain backward compatibility during transitions using feature toggles or parallel versions.
  • Implement proper deprecation policies with clear migration timelines.

Common mistakes

  • Breaking backward compatibility without proper migration strategy.
  • Using only URL versioning without considering header or content-type approaches.

Sample answer

I use multiple versioning strategies depending on the context. For major changes, I implement URL path versioning like @RequestMapping('/api/v1/orders') and @RequestMapping('/api/v2/orders') in separate controllers. For minor changes, I use header versioning with @RequestMapping(headers = 'API-Version=2.0'). Content negotiation works well for response format changes using produces = 'application/vnd.company.order-v2+json'.

The key is maintaining backward compatibility, I keep both versions running simultaneously, use feature toggles to control rollout, and implement proper deprecation notices in response headers. I monitor API usage through Spring Boot Actuator metrics to understand when clients have migrated before removing old versions.

How to level up

  • Implement automated contract testing to ensure backward compatibility during versioning.
  • Use Spring Cloud Gateway to route different API versions to appropriate service instances.
  • Create version-specific DTOs and use MapStruct for clean conversion between versions.

Follow-up questions to expect

  • How do you handle database schema changes when versioning APIs?
  • What's your strategy for deprecating old API versions?
  • How do you test backward compatibility across versions?
Practice this question with AI feedback →
How do you implement security for microservice-to-microservice communication?
hard

What they're really asking

This tests your understanding of microservice security architecture and zero-trust principles. The interviewer wants to see if you can implement authentication, authorization, and secure communication between services.

How you'll be scored

Weak

Mentions basic concepts like JWT tokens without understanding service-to-service authentication challenges.

Average

Explains JWT or OAuth2 for service communication but doesn't address network security or authorization patterns.

Strong

Demonstrates comprehensive security approach including mutual TLS, service mesh, OAuth2 client credentials, and proper secret management with Spring Security implementation details.

How to structure your answer

  1. Explain the zero-trust security model for microservices.
  2. Present authentication strategies: JWT, OAuth2 client credentials, mutual TLS.
  3. Show Spring Security implementation for service-to-service calls.
  4. Address authorization patterns and fine-grained access control.
  5. Discuss secret management and certificate rotation.

Key points to hit

  • Use OAuth2 client credentials flow for service-to-service authentication.
  • Implement mutual TLS for transport-level security between services.
  • Spring Security OAuth2 client provides seamless service authentication.
  • Centralize authorization decisions using policy engines or service mesh.

Common mistakes

  • Sharing user JWTs between services instead of using service-specific tokens.
  • Not implementing proper certificate management and rotation for mTLS.

Sample answer

I implement service-to-service security using OAuth2 client credentials flow where each service authenticates with an authorization server to get service-specific access tokens. In Spring Boot, I configure OAuth2 client in application.yml and use @RegisteredOAuth2AuthorizedClient to automatically inject tokens into service calls.

For transport security, I implement mutual TLS using Spring Boot's server.ssl configuration with client certificate verification. I use Spring Cloud Gateway as a security gateway to validate tokens and route requests. For sensitive services, I implement fine-grained authorization using Spring Method Security with @PreAuthorize annotations that check service scopes.

Secret management happens through Spring Cloud Vault or Kubernetes secrets with automatic rotation.

How to level up

  • Implement service mesh like Istio for automatic mTLS and policy enforcement across all services.
  • Use Spring Security's OAuth2 Resource Server to validate service tokens with proper scope checking.
  • Implement distributed tracing with security context propagation to maintain audit trails across service calls.

Follow-up questions to expect

  • How do you handle certificate rotation in a large microservices environment?
  • What's your approach to authorization when services need different access levels?
  • How do you secure service discovery and configuration management?
Practice this question with AI feedback →
What are some common challenges in a microservices architecture and how do you address them?
hard

What they're really asking

This tests your practical experience with microservices complexity and your problem-solving approach. The interviewer wants to see if you understand real-world challenges beyond the theoretical benefits.

How you'll be scored

Weak

Lists generic challenges without specific solutions or Spring Boot context.

Average

Identifies key challenges like distributed tracing and provides basic solutions but lacks depth in implementation details.

Strong

Demonstrates deep understanding of microservices challenges with concrete Spring Boot solutions, tooling choices, and lessons learned from production experience.

How to structure your answer

  1. Identify major microservice challenges: distributed tracing, data consistency, service discovery.
  2. Present Spring Boot and Spring Cloud solutions for each challenge.
  3. Discuss monitoring and observability requirements.
  4. Address deployment and operational complexity.
  5. Share lessons learned and anti-patterns to avoid.

Key points to hit

  • Distributed tracing solved with Spring Cloud Sleuth and Zipkin integration.
  • Service discovery and load balancing through Spring Cloud Netflix or Kubernetes.
  • Configuration management using Spring Cloud Config with Git-based versioning.
  • Circuit breaker pattern implementation with Hystrix or Resilience4j.

Common mistakes

  • Over-engineering small applications with microservices complexity.
  • Not implementing proper monitoring and alerting before going to production.

Sample answer

The biggest challenges I've faced include distributed tracing, data consistency, and operational complexity. For tracing, I use Spring Cloud Sleuth with Zipkin to track requests across services, it automatically adds correlation IDs to logs and HTTP headers.

Data consistency is handled through event sourcing and eventual consistency patterns, using Spring Cloud Stream with RabbitMQ for reliable message delivery. Service discovery uses Spring Cloud Netflix Eureka, though I'm moving toward Kubernetes-native discovery. Configuration management happens through Spring Cloud Config Server backed by Git repositories with environment-specific profiles.

The operational complexity is significant, I use Spring Boot Actuator for health checks, Prometheus for metrics collection, and implement circuit breakers with Resilience4j to prevent cascade failures. The key lesson is to start with a modular monolith and extract services only when team boundaries and scaling needs justify the complexity.

How to level up

  • Implement comprehensive service mesh observability with distributed tracing, metrics, and logs correlation.
  • Use contract-driven development with Spring Cloud Contract to prevent integration issues.
  • Establish clear data ownership boundaries and avoid distributed transactions across service boundaries.

Follow-up questions to expect

  • How do you decide when to split a monolith into microservices?
  • What's your approach to handling distributed system failures?
  • How do you manage database changes across multiple microservices?
Practice this question with AI feedback →
How do you deploy microservices in production? (Docker, Kubernetes)
hard

What they're really asking

The interviewer wants to see if you have production deployment experience and understand the containerization pipeline from building Docker images to orchestrating them with Kubernetes.

How you'll be scored

Weak

Describes manual deployment steps like copying JAR files to servers.

Average

Understands Docker containerization but cannot explain Kubernetes orchestration or CI/CD integration.

Strong

Demonstrates the full pipeline from Dockerfile or Buildpacks to Kubernetes manifests, including health checks, resource limits, config management, and rolling deployments.

How to structure your answer

  1. Explain containerizing Spring Boot applications with Docker.
  2. Detail Kubernetes deployment configuration.
  3. Discuss health checks and readiness probes.
  4. Cover CI/CD pipeline integration.

Key points to hit

  • Spring Boot applications are containerized using multi-stage Dockerfiles or Cloud Native Buildpacks via spring-boot:build-image which creates optimized layered images.
  • Kubernetes Deployment manifests define replicas, resource limits, and rolling update strategies for zero-downtime deployments.
  • Spring Boot Actuator /health/liveness and /health/readiness endpoints map directly to Kubernetes liveness and readiness probes.
  • Configuration is externalized using Kubernetes ConfigMaps and Secrets, injected as environment variables or mounted files.

Common mistakes

  • Building Docker images with the fat JAR as a single layer, which means every rebuild pushes the entire image including unchanged dependencies.
  • Not configuring Kubernetes probes, which means Kubernetes cannot detect unhealthy pods or pods that are not ready to receive traffic.

Sample answer

I start by containerizing each Spring Boot service. I use Spring Boot's built-in Buildpacks support with mvn spring-boot:build-image, which creates a layered Docker image that separates dependencies from application code for efficient caching. Alternatively, I write a multi-stage Dockerfile where the first stage builds with Maven and the second stage uses a slim JRE image.

In Kubernetes, I create a Deployment manifest with resource requests and limits, a rolling update strategy with maxSurge and maxUnavailable, and health probes pointing to Actuator endpoints. The liveness probe hits /actuator/health/liveness to restart stuck pods. The readiness probe hits /actuator/health/readiness to remove pods from the load balancer while they are starting up.

Configuration comes from ConfigMaps for non-sensitive values and Secrets for passwords and API keys, both injected as environment variables. My CI/CD pipeline in GitHub Actions builds the image, pushes it to a container registry, and applies the Kubernetes manifests using kubectl or Helm.

How to level up

  • Mention JVM options for containers like -XX:MaxRAMPercentage and -XX:+UseContainerSupport for proper memory management inside containers.
  • Discuss Helm charts for templating Kubernetes manifests across environments with different configurations.
  • Explain graceful shutdown with spring.lifecycle.timeout-per-shutdown-phase for draining in-flight requests before pod termination.

Follow-up questions to expect

  • How do you handle database migrations during Kubernetes deployments?
  • What is the difference between liveness and readiness probes?
  • How do you implement canary deployments for microservices?
Practice this question with AI feedback →
How does a Spring Boot microservice discover dependent microservices?
hard

What they're really asking

The interviewer wants to see if you understand service discovery patterns and can choose the right approach based on your deployment environment, whether that is Kubernetes-native or Spring Cloud based.

How you'll be scored

Weak

Hardcodes service URLs in configuration and does not understand service discovery.

Average

Mentions Eureka but does not discuss Kubernetes-native discovery or the trade-offs between approaches.

Strong

Explains both client-side (Eureka) and platform-native (Kubernetes DNS) service discovery, discusses the trade-offs, and shows configuration in Spring Boot.

How to structure your answer

  1. Explain why service discovery is needed in microservices.
  2. Detail client-side discovery with Spring Cloud (Eureka)
  3. Detail platform-native discovery with Kubernetes.
  4. Compare approaches and recommend based on environment.

Key points to hit

  • Service discovery allows microservices to find each other dynamically without hardcoded URLs, essential when instances scale up and down.
  • Spring Cloud Netflix Eureka provides client-side discovery where services register themselves and clients query the registry.
  • Kubernetes provides built-in service discovery through DNS and Service resources, where service-name.namespace.svc.cluster.local resolves to healthy pod IPs.
  • Spring Cloud Kubernetes integrates Spring's service discovery abstraction with Kubernetes native services for consistent programming model.

Common mistakes

  • Running Eureka on Kubernetes when Kubernetes already provides built-in service discovery, adding unnecessary infrastructure complexity.
  • Hardcoding IP addresses or ports in configuration files, which breaks when services scale or relocate.

Sample answer

Service discovery depends on the deployment platform. In Spring Cloud environments without Kubernetes, I use Eureka. Each service includes spring-cloud-starter-netflix-eureka-client and registers itself on startup. When the Order Service needs to call the Inventory Service, it queries Eureka for healthy instances and uses client-side load balancing with Spring Cloud LoadBalancer.

In Kubernetes, I use the built-in service discovery because it is simpler and more reliable. Each microservice is exposed through a Kubernetes Service resource, and other services reach it via DNS at inventory-service.production.svc.cluster.local. I configure Spring Boot with spring.cloud.discovery.client.simple or spring-cloud-starter-kubernetes to integrate Kubernetes services with Spring's DiscoveryClient and @LoadBalanced WebClient.

My recommendation is to use Kubernetes-native discovery when running on Kubernetes, as it eliminates the operational overhead of running a separate Eureka cluster.

How to level up

  • Discuss service mesh solutions like Istio that provide advanced service discovery with traffic management and mTLS without application changes.
  • Mention HashiCorp Consul as a platform-agnostic alternative to Eureka that supports both service discovery and distributed configuration.
  • Explain how to implement custom health indicators that control service registration based on downstream dependency availability.

Follow-up questions to expect

  • How does client-side load balancing work with Spring Cloud LoadBalancer?
  • What happens when a service instance crashes and has not deregistered from Eureka?
  • How do you implement service discovery across multiple Kubernetes clusters?
Practice this question with AI feedback →
What is the CQRS (Command Query Responsibility Segregation) pattern?
hard

What they're really asking

The interviewer wants to see if you understand advanced microservices architecture patterns and can explain when separating read and write models provides meaningful benefits over simpler architectures.

How you'll be scored

Weak

Has never heard of CQRS or confuses it with basic CRUD separation.

Average

Understands the concept of separate read and write models but cannot explain the implementation or when it is appropriate.

Strong

Explains the pattern thoroughly, demonstrates implementation with event sourcing, and articulates the complexity trade-offs and appropriate use cases.

How to structure your answer

  1. Define CQRS as separating read and write operations into different models.
  2. Explain why this separation is useful.
  3. Show implementation patterns in Spring Boot.
  4. Discuss trade-offs and when to use it.

Key points to hit

  • CQRS separates the write model (commands) from the read model (queries), allowing each to be optimized independently for their specific workload.
  • The write side handles business logic, validation, and domain events, while the read side maintains denormalized projections optimized for query performance.
  • Changes from the write model are propagated to the read model through domain events, creating eventual consistency between the two.
  • CQRS is often paired with event sourcing where the write model stores events instead of current state, enabling full audit trails and temporal queries.

Common mistakes

  • Applying CQRS to every service when it adds significant complexity and is only justified for services with very different read and write patterns.
  • Not understanding the eventual consistency implications that come with separate read and write stores.

Sample answer

CQRS separates the read and write sides of an application into distinct models. In a traditional CRUD service, the same model handles both inserts and queries. With CQRS, the command side handles writes with a rich domain model, business rules, and validation. It publishes domain events when state changes.

The query side consumes those events and builds denormalized read models optimized for specific queries. In Spring Boot, I implement the command side with a standard service layer that publishes events to Kafka. The query side is a separate service that listens to these events and maintains read-optimized projections in Elasticsearch or Redis.

For example, an Order Service command side stores normalized orders in PostgreSQL. The query side builds a denormalized projection that joins order, product, and customer data into a single document for the order detail API. This lets me scale reads and writes independently and optimize each for its workload.

But CQRS adds significant complexity with eventual consistency, so I only use it when read and write patterns are drastically different.

How to level up

  • Mention Axon Framework for Spring Boot, which provides out-of-the-box CQRS and event sourcing infrastructure.
  • Discuss how to handle the eventually consistent gap in the UI with patterns like optimistic updates or loading indicators.
  • Explain how event sourcing complements CQRS by making the write model an append-only event log that can rebuild any read model from scratch.

Follow-up questions to expect

  • When is CQRS overkill and when is it justified?
  • How does CQRS relate to event sourcing?
  • How do you handle the consistency gap between command and query models?
Practice this question with AI feedback →
How do you handle distributed transactions across microservices?
hard

What they're really asking

The interviewer wants to see if you understand why two-phase commit does not work well in microservices and can implement saga patterns for maintaining data consistency across service boundaries.

How you'll be scored

Weak

Suggests using distributed XA transactions, which do not scale in microservices architectures.

Average

Knows about the saga pattern but cannot explain the two types (orchestration vs choreography) or compensation logic.

Strong

Explains both saga types with concrete examples, discusses compensation strategies, and understands the idempotency requirements for reliable distributed transactions.

How to structure your answer

  1. Explain why traditional distributed transactions do not work in microservices.
  2. Define the saga pattern as the alternative.
  3. Compare choreography-based and orchestration-based sagas.
  4. Discuss compensation, idempotency, and error handling.

Key points to hit

  • Two-phase commit (2PC) does not scale in microservices because it requires locking resources across services, creating tight coupling and blocking.
  • The saga pattern breaks a distributed transaction into a sequence of local transactions, each within a single service, coordinated through events or an orchestrator.
  • Choreography-based sagas use events: each service publishes an event after its local transaction, and the next service reacts to it.
  • Orchestration-based sagas use a central coordinator that directs each service to perform its step and handles compensation on failure.

Common mistakes

  • Trying to implement distributed ACID transactions across microservices when the saga pattern with eventual consistency is the microservices approach.
  • Not implementing compensating transactions for every step in the saga, which means a failure partway through leaves the system in an inconsistent state.

Sample answer

Traditional distributed transactions using two-phase commit create tight coupling and do not scale in microservices. Instead, I use the saga pattern. For a purchase flow spanning Order, Payment, and Inventory services, I implement it as a saga where each service completes its local transaction and publishes an event.

In choreography, the Order Service creates an order and publishes OrderCreated. The Payment Service listens, charges the card, and publishes PaymentCompleted. The Inventory Service listens, reserves stock, and publishes StockReserved. If any step fails, like payment declining, that service publishes a failure event and upstream services execute compensating transactions to undo their changes.

In Spring Boot, I implement this with Spring Cloud Stream and Kafka for event publishing. For complex sagas, I use orchestration where a SagaOrchestrator service directs each step and handles the compensation sequence on failure.

Every service must be idempotent because events can be delivered multiple times, so I use unique transaction IDs to detect duplicates.

How to level up

  • Discuss the transactional outbox pattern for atomically publishing events alongside database changes, preventing lost events.
  • Mention Axon Framework or Temporal.io as saga orchestration frameworks that handle the complex state management.
  • Explain how to handle saga timeouts when a service does not respond with either success or failure events.

Follow-up questions to expect

  • What is the transactional outbox pattern?
  • How do you handle a saga step that partially succeeds?
  • When would you choose orchestration over choreography for a saga?
Practice this question with AI feedback →

Ready to put this into practice?

Try these questions in a mock interview →

Still applying for jobs? Let Auto Apply do it

Spring Boot Testing (Beginner) (3)

How does Spring Boot simplify writing tests?
easy

What they're really asking

The interviewer wants to see if you understand the testing infrastructure Spring Boot provides and how it reduces the boilerplate needed to write effective tests.

How you'll be scored

Weak

Does not know about Spring Boot's testing support beyond basic JUnit.

Average

Mentions @SpringBootTest but cannot explain the different test slice annotations or embedded database support.

Strong

Explains the full testing toolkit including @SpringBootTest, test slice annotations, auto-configured mocks, embedded databases, and the spring-boot-starter-test dependency.

How to structure your answer

  1. Explain the spring-boot-starter-test dependency and what it bundles.
  2. Describe @SpringBootTest for integration tests.
  3. Discuss test slice annotations for focused testing.
  4. Mention auto-configured test utilities.

Key points to hit

  • spring-boot-starter-test bundles JUnit 5, Mockito, AssertJ, Hamcrest, JSONassert, and Spring Test in a single dependency.
  • @SpringBootTest creates a full application context for integration testing, with options for mock or real web environments.
  • Test slice annotations like @WebMvcTest, @DataJpaTest, and @JsonTest create minimal contexts focused on specific layers, making tests faster.
  • Auto-configured utilities like TestRestTemplate, MockMvc, and @MockBean eliminate boilerplate setup for common testing scenarios.

Common mistakes

  • Using @SpringBootTest for every test when test slice annotations provide faster, more focused alternatives.
  • Not knowing that @DataJpaTest auto-configures an embedded H2 database, which means you do not need to set up a test database manually.

Sample answer

Spring Boot simplifies testing at every level. It starts with the spring-boot-starter-test dependency, which bundles JUnit 5, Mockito, AssertJ, and Spring Test so you do not manage individual testing library versions. For integration tests, @SpringBootTest boots the full application context and lets you test with a real or mock web environment.

For focused unit tests, Spring Boot provides slice annotations. @WebMvcTest creates only the web layer context for testing controllers with MockMvc. @DataJpaTest configures only the JPA layer with an embedded H2 database for repository testing. @MockBean lets you replace any bean in the context with a Mockito mock.

This means I can test my controller layer without starting the full application, with a mock service injected automatically. The result is that I spend time writing test logic instead of test infrastructure.

How to level up

  • Mention Testcontainers for integration testing with real databases, message brokers, and other infrastructure instead of embedded alternatives.
  • Discuss @TestConfiguration for defining test-specific beans that override production configurations.
  • Explain how @DirtiesContext controls context caching and when to use it versus letting Spring cache test contexts for speed.

Follow-up questions to expect

  • What is the difference between @SpringBootTest and @WebMvcTest?
  • How do you test with a real database instead of an embedded one?
  • When would you use Testcontainers over embedded databases?
Practice this question with AI feedback →
What starter dependency do you need for testing a Spring Boot application?
easy

What they're really asking

This tests basic Spring Boot testing setup knowledge. The interviewer wants to see if you understand the fundamental testing infrastructure and can get a test environment running.

How you'll be scored

Weak

Cannot name the correct starter dependency or gives incorrect information.

Average

Correctly identifies spring-boot-starter-test but provides no additional context.

Strong

Names the dependency and explains why it's needed or what it provides.

How to structure your answer

  1. Name the specific starter dependency.
  2. Briefly explain what it provides.
  3. Mention how it integrates with Spring Boot's testing approach.

Key points to hit

  • spring-boot-starter-test is the core testing starter dependency.
  • It follows Spring Boot's convention over configuration for testing.
  • Includes JUnit, Mockito, and Spring Test framework out of the box.
  • Provides test slice annotations for focused testing.

Common mistakes

  • Confusing it with spring-test or junit dependencies alone.
  • Not understanding that it's a comprehensive testing stack, not just JUnit.

Sample answer

You need spring-boot-starter-test as your main testing dependency. This starter brings in everything you need for comprehensive Spring Boot testing, including JUnit 5, Mockito for mocking, Spring Test framework for integration testing, and all the test slice annotations like @WebMvcTest and @DataJpaTest.

It follows Spring Boot's philosophy of providing everything you need in one dependency so you don't have to manually configure your testing stack.

How to level up

  • Mention that it includes TestContainers support starting from Spring Boot 2.2.
  • Explain how it integrates with Spring Boot's auto-configuration for tests.

Follow-up questions to expect

  • What specific testing libraries does spring-boot-starter-test include?
  • How do you exclude certain testing dependencies if you don't need them?
  • What's the difference between JUnit 4 and JUnit 5 support in Spring Boot?
Practice this question with AI feedback →
What dependencies does spring-boot-starter-test bring to the classpath?
easy

What they're really asking

This tests deeper knowledge of Spring Boot's testing ecosystem. The interviewer wants to verify you understand what tools are available and can leverage the full testing stack effectively.

How you'll be scored

Weak

Lists only one or two dependencies or provides incorrect information about what's included.

Average

Names several key dependencies like JUnit and Mockito but misses important ones.

Strong

Comprehensively lists the major testing frameworks and explains their roles in the testing ecosystem.

How to structure your answer

  1. List the core testing frameworks included.
  2. Mention mocking and assertion libraries.
  3. Cover Spring-specific testing utilities.
  4. Note any additional helper libraries.

Key points to hit

  • JUnit 5 as the primary testing framework.
  • Mockito for mocking dependencies.
  • Spring Test and Spring Boot Test for integration testing.
  • AssertJ for fluent assertions and Hamcrest for matchers.

Common mistakes

  • Assuming it still defaults to JUnit 4 instead of JUnit 5.
  • Not mentioning Spring-specific testing utilities like @MockBean.

Sample answer

spring-boot-starter-test brings JUnit 5 as the main testing framework, Mockito for creating mocks and spies, Spring Test framework for integration testing, AssertJ for fluent assertions, Hamcrest for additional matchers, and JSONPath for JSON testing. It also includes Spring Boot's testing annotations like @MockBean and @SpyBean, plus JsonTest utilities for testing JSON serialization.

This gives you a complete testing toolkit without having to manage individual dependency versions.

How to level up

  • Mention that it includes WebTestClient for reactive testing scenarios.
  • Explain how dependency versions are managed through Spring Boot's BOM.

Follow-up questions to expect

  • How do you exclude JUnit 4 if it's accidentally pulled in by other dependencies?
  • What's the difference between @MockBean and Mockito's @Mock?
  • How do you add TestContainers to your Spring Boot test setup?
Practice this question with AI feedback →

Spring Boot Testing (Intermediate) (11)

What does @SpringBootTest do and how does it interact with @SpringBootApplication?
medium

What they're really asking

This tests understanding of full integration testing in Spring Boot. The interviewer wants to see if you know how @SpringBootTest bootstraps the entire application context and its relationship with the main application class.

How you'll be scored

Weak

Vague understanding that it's for testing without explaining the application context loading.

Average

Explains it loads the full application context but doesn't connect it to @SpringBootApplication.

Strong

Demonstrates understanding of how it finds and uses @SpringBootApplication to bootstrap the complete Spring context for testing.

How to structure your answer

  1. Explain what @SpringBootTest does fundamentally.
  2. Describe how it finds @SpringBootApplication.
  3. Explain the full application context loading.
  4. Mention configuration options available.

Key points to hit

  • @SpringBootTest loads the complete Spring application context.
  • It searches for @SpringBootApplication class to determine configuration.
  • Creates the same beans and configuration as production runtime.
  • Supports different web environments like MOCK, RANDOM_PORT, or DEFINED_PORT.

Common mistakes

  • Thinking it only loads partial context like slice tests do.
  • Not understanding it replicates the full production Spring Boot startup process.

Sample answer

@SpringBootTest creates a full Spring application context just like when you run your actual application. It automatically searches up the package hierarchy to find your @SpringBootApplication annotated class and uses that as the entry point to load all your beans, auto-configurations, and components.

This means you get the exact same Spring context in your test as you would in production, including all your services, repositories, and configurations. You can control the web environment with webEnvironment parameter, like using RANDOM_PORT for full integration tests with a real embedded server.

How to level up

  • Explain how to use classes attribute to specify a different configuration class than @SpringBootApplication.
  • Mention how @TestConfiguration can override beans for testing scenarios.

Follow-up questions to expect

  • What are the different webEnvironment options and when would you use each?
  • How do you override specific beans when using @SpringBootTest?
  • What's the performance impact of using @SpringBootTest compared to slice tests?
Practice this question with AI feedback →
When do you want to use @SpringBootTest vs slice test annotations?
medium

What they're really asking

This tests strategic thinking about test performance and scope. The interviewer wants to see if you understand when full integration testing is appropriate versus focused slice testing for faster feedback loops.

How you'll be scored

Weak

Cannot explain the difference or when to use each approach.

Average

Understands @SpringBootTest is slower but doesn't clearly articulate when to use slice tests.

Strong

Demonstrates clear understanding of test pyramid principles and can choose the right testing approach based on what needs to be verified.

How to structure your answer

  1. Explain the performance and scope differences.
  2. Describe when full context is necessary.
  3. Explain when slice tests are more appropriate.
  4. Mention test pyramid principles.

Key points to hit

  • @SpringBootTest loads full context, slower but tests complete integration.
  • Slice tests like @WebMvcTest, @DataJpaTest load only relevant components.
  • Use slice tests for focused unit testing of specific layers.
  • Use @SpringBootTest for end-to-end integration scenarios.

Common mistakes

  • Always using @SpringBootTest without considering faster alternatives.
  • Using slice tests when you actually need cross-layer integration testing.

Sample answer

I use @SpringBootTest when I need to test the complete integration flow between multiple layers, like testing a REST endpoint that calls a service which uses a repository. But for most tests, slice annotations are much faster because they only load the components needed for that layer.

For example, @WebMvcTest only loads the web layer for controller testing, and @DataJpaTest only configures JPA repositories. This follows the test pyramid principle where you have many fast, focused unit tests and fewer slow integration tests. I typically use @SpringBootTest for critical happy path scenarios and slice tests for detailed edge case testing.

How to level up

  • Explain how @MockBean can be used with slice tests to mock dependencies from other layers.
  • Mention that slice tests can be combined, like @WebMvcTest with @Import for specific services.

Follow-up questions to expect

  • Which slice test annotation would you use for testing a service layer?
  • How do you test cross-cutting concerns like security with slice tests?
  • What's your strategy for maintaining good test coverage with this approach?
Practice this question with AI feedback →
What does @SpringBootTest auto-configure?
medium

What they're really asking

This tests deep understanding of Spring Boot's testing auto-configuration. The interviewer wants to see if you know what infrastructure Spring Boot provides automatically for integration testing.

How you'll be scored

Weak

Cannot explain what gets auto-configured or gives incorrect information.

Average

Mentions some auto-configurations like embedded database but misses key components.

Strong

Comprehensively explains the testing infrastructure that gets configured and how it differs from production.

How to structure your answer

  1. Explain the testing-specific auto-configurations.
  2. Cover embedded servers and databases.
  3. Mention test property sources.
  4. Describe MockBean and testing utilities setup.

Key points to hit

  • Embedded web server (Tomcat/Jetty) for web environment testing.
  • In-memory database like H2 if no other datasource configured.
  • Test property sources and application-test.properties loading.
  • @MockBean and @SpyBean support for replacing production beans.

Common mistakes

  • Thinking it uses production database by default instead of embedded.
  • Not understanding that it creates a separate testing-optimized environment.

Sample answer

@SpringBootTest auto-configures a complete testing environment that's optimized for integration testing. It starts an embedded web server on a random port if you specify webEnvironment, sets up an in-memory database like H2 if you don't have a specific test datasource configured, and loads test-specific properties from application-test.properties.

It also enables @MockBean and @SpyBean annotations so you can easily replace production beans with mocks in your test context. The goal is to create an environment that's as close to production as possible but isolated and repeatable for testing.

How to level up

  • Explain how TestPropertySource can override specific properties for testing.
  • Mention that @TestConfiguration classes are automatically detected and applied.

Follow-up questions to expect

  • How do you configure @SpringBootTest to use a real database instead of embedded?
  • What happens if you have both @MockBean and the real bean in your test context?
  • How do you customize the embedded server configuration for testing?
Practice this question with AI feedback →
What is @WebMvcTest and what does it auto-configure?
medium

What they're really asking

The interviewer wants to see if you know how to write fast, focused controller tests without loading the entire application context.

How you'll be scored

Weak

Does not know @WebMvcTest or uses @SpringBootTest for all controller tests.

Average

Knows @WebMvcTest is for testing controllers but cannot list what it auto-configures or what it excludes.

Strong

Explains exactly what @WebMvcTest configures and excludes, demonstrates testing with MockMvc and @MockBean, and knows when to use it versus @SpringBootTest.

How to structure your answer

  1. Define @WebMvcTest as a test slice annotation for the web layer.
  2. List what it auto-configures.
  3. List what it excludes.
  4. Show a typical test setup.

Key points to hit

  • @WebMvcTest creates a minimal Spring context that includes only web layer components: @Controller, @ControllerAdvice, @JsonComponent, filters, and WebMvcConfigurer.
  • It auto-configures MockMvc for simulating HTTP requests without starting a real server.
  • It does NOT scan @Service, @Repository, or @Component beans. You must provide dependencies with @MockBean.
  • You can target a specific controller with @WebMvcTest(UserController.class) to further narrow the context.

Common mistakes

  • Using @SpringBootTest for controller unit tests when @WebMvcTest is faster because it loads only the web layer.
  • Forgetting to mock service dependencies with @MockBean, which causes NoSuchBeanDefinitionException because @WebMvcTest does not scan service classes.

Sample answer

@WebMvcTest is a test slice annotation that creates a minimal application context focused on the web layer. It auto-configures MockMvc, Jackson ObjectMapper, message converters, @ControllerAdvice classes, and Spring Security filters. Crucially, it does not scan your @Service or @Repository beans. You need to provide them with @MockBean.

I typically write @WebMvcTest(OrderController.class) to test just that controller. Then I @MockBean the OrderService and configure its behavior with Mockito when() calls. I inject MockMvc and use it to perform GET, POST, PUT requests, then assert the status code, response body, and headers.

These tests are fast because they do not load a database, message brokers, or other infrastructure. They verify that your controller correctly handles request parameters, serializes responses, and returns the right status codes.

How to level up

  • Mention that @WebMvcTest includes Spring Security auto-configuration by default, so you may need @WithMockUser for authenticated endpoint tests.
  • Discuss @AutoConfigureJsonTesters for testing JSON serialization alongside controller tests.
  • Explain that @WebMvcTest is just one slice, and you can combine it with @Import for including additional configuration classes.

Follow-up questions to expect

  • How do you test authenticated endpoints with @WebMvcTest?
  • What is the difference between @WebMvcTest and @SpringBootTest with MockMvc?
  • How do you test file upload endpoints with @WebMvcTest?
Practice this question with AI feedback →
What is MockMvc and how do you use it for testing controllers?
medium

What they're really asking

The interviewer wants to see if you can write effective controller tests that verify HTTP interaction without starting a real server.

How you'll be scored

Weak

Has not used MockMvc or tests controllers by calling methods directly.

Average

Can perform basic GET requests with MockMvc but does not test request bodies, headers, or detailed response assertions.

Strong

Demonstrates fluent MockMvc API for various HTTP methods, content types, request body serialization, response assertions, and integration with security testing.

How to structure your answer

  1. Define MockMvc as a server-side test framework for Spring MVC.
  2. Show how to set up MockMvc in tests.
  3. Demonstrate common testing patterns.
  4. Discuss response assertions and verification.

Key points to hit

  • MockMvc simulates HTTP requests to your controllers without starting a real HTTP server, making tests fast and deterministic.
  • It is auto-configured by @WebMvcTest or can be set up with @AutoConfigureMockMvc in @SpringBootTest.
  • Use perform() to execute requests, andExpect() to assert status codes, headers, and response body, and andReturn() to get the full response for custom assertions.
  • Supports all HTTP methods, request parameters, path variables, headers, multipart uploads, and JSON/XML request bodies.

Common mistakes

  • Only testing happy path responses without verifying error handling, validation failures, and edge cases.
  • Testing controller methods by calling them directly like regular Java methods, which bypasses Spring MVC's request mapping, serialization, and exception handling.

Sample answer

MockMvc is Spring's test framework for testing the web layer without starting a real HTTP server. It processes requests through the full Spring MVC stack including request mapping, serialization, validation, and exception handling. I set it up by injecting MockMvc in a @WebMvcTest class. For a GET test, I write mockMvc.perform(get("/api/users/1")).andExpect(status().isOk()).andExpect(jsonPath("$.name").value("John")).

For a POST test with a JSON body, I use mockMvc.perform(post("/api/users").contentType(MediaType.APPLICATION_JSON).content(objectMapper.writeValueAsString(createUserRequest))).andExpect(status().isCreated()). I also test error cases like mockMvc.perform(get("/api/users/999")).andExpect(status().isNotFound()) to verify my @ControllerAdvice handles exceptions correctly. The jsonPath assertions let me verify specific fields in the response without deserializing the entire object.

How to level up

  • Mention andDo(print()) for debugging, which prints the full request and response details to the console.
  • Discuss using @WithMockUser and @WithAnonymousUser for testing secured endpoints with different authentication states.
  • Explain MockMvcResultMatchers.content().json() for comparing entire JSON response bodies against expected JSON strings.

Follow-up questions to expect

  • How do you test multipart file uploads with MockMvc?
  • How do you test authenticated endpoints using MockMvc?
  • What is the difference between MockMvc and TestRestTemplate?
Practice this question with AI feedback →
What is the difference between @MockBean and @Mock?
medium

What they're really asking

The interviewer wants to see if you understand the difference between Mockito mocks and Spring-context-aware mocks, and can choose the right one based on your testing approach.

How you'll be scored

Weak

Does not know the difference or uses them interchangeably without understanding the implications.

Average

Knows @MockBean is for Spring context and @Mock is for unit tests but cannot explain the practical implications.

Strong

Explains the context replacement mechanism of @MockBean, the lightweight nature of @Mock, and when each is appropriate for different test types.

How to structure your answer

  1. Define @Mock as a Mockito annotation for plain unit tests.
  2. Define @MockBean as a Spring Boot Test annotation for integration tests.
  3. Explain how @MockBean interacts with the application context.
  4. Recommend when to use each.

Key points to hit

  • @Mock is a Mockito annotation that creates a mock object in isolation without any Spring context involvement, used with @ExtendWith(MockitoExtension.class)
  • @MockBean is a Spring Boot Test annotation that creates a mock and replaces (or adds) it in the Spring application context.
  • @MockBean causes the application context to be modified, which can trigger context recreation and slow down test suites if overused.
  • Use @Mock for pure unit tests where you test a class in isolation, and @MockBean for slice or integration tests where the mock needs to live in the Spring context.

Common mistakes

  • Using @MockBean in pure unit tests when @Mock is lighter and faster because it does not require a Spring context.
  • Overusing @MockBean with different configurations across tests, causing excessive context recreation and slow test suites.

Sample answer

@Mock is a Mockito annotation that creates a standalone mock object. You use it in unit tests with @ExtendWith(MockitoExtension.class) and inject it manually via constructor or @InjectMocks.

There is no Spring context involved, so these tests are extremely fast. @MockBean is a Spring Boot Test annotation that creates a Mockito mock and registers it in the Spring application context, replacing any existing bean of that type.

You use it in @WebMvcTest or @SpringBootTest when the component under test is wired by Spring and needs its dependencies mocked through the context. For example, when testing a controller with @WebMvcTest, I use @MockBean for the service because MockMvc dispatches requests through the Spring context and the controller needs to find its dependencies there.

The trade-off is that @MockBean modifies the context cache. If different tests use different @MockBean combinations, Spring creates separate contexts, which slows down the test suite.

How to level up

  • Mention @SpyBean as the Spring Boot Test equivalent of @Spy for partial mocking within the application context.
  • Discuss how to minimize context recreation by keeping @MockBean declarations consistent across test classes.
  • Explain that in Spring Boot 3.4+, @MockitoBean and @MockitoSpyBean are the new replacements with better context caching behavior.

Follow-up questions to expect

  • How does @MockBean affect Spring's test context caching?
  • When would you use @SpyBean instead of @MockBean?
  • How do you verify mock interactions in Spring Boot tests?
Practice this question with AI feedback →
What is @DataJpaTest and when do you use it?
medium

What they're really asking

The interviewer wants to see if you know how to write focused repository tests that verify data access logic without loading the full application.

How you'll be scored

Weak

Tests repositories by loading the full application context with @SpringBootTest.

Average

Knows @DataJpaTest is for repository testing but cannot explain what it auto-configures or the embedded database behavior.

Strong

Explains the auto-configured components, embedded database replacement, transaction rollback behavior, and when to use Testcontainers instead.

How to structure your answer

  1. Define @DataJpaTest as a test slice for JPA repositories.
  2. List what it auto-configures.
  3. Explain the embedded database behavior.
  4. Discuss transaction management in tests.

Key points to hit

  • @DataJpaTest creates a minimal context with only JPA-related components: repositories, EntityManager, TestEntityManager, and Flyway/Liquibase migrations.
  • It auto-configures an embedded in-memory database (H2, Derby, or HSQLDB) replacing your production database, unless overridden.
  • Each test method is wrapped in a transaction that rolls back automatically, keeping the database clean between tests.
  • Use TestEntityManager to set up test data by persisting entities directly, bypassing repository methods you are testing.

Common mistakes

  • Relying on embedded H2 for tests when your production database is PostgreSQL, which can hide SQL dialect differences and constraint behavior.
  • Not understanding that @DataJpaTest transactions auto-rollback, so using @Commit or @Rollback(false) to debug test data can leave the database dirty.

Sample answer

@DataJpaTest is a test slice annotation for testing JPA repositories. It creates a minimal context that includes your repository interfaces, EntityManager, TestEntityManager, and any Flyway or Liquibase migrations. It does not load controllers, services, or other components.

By default, it replaces your configured DataSource with an embedded H2 database, so you do not need a running database for tests. Each test method runs in a transaction that rolls back after completion, keeping tests isolated. I use TestEntityManager to insert test data directly, then call my repository methods and assert the results.

For example, I persist a User entity with TestEntityManager, then call userRepository.findByEmail("test@example.com") and verify it returns the correct user. When I need to test with a real database to catch SQL dialect issues, I add @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) and use Testcontainers to spin up a PostgreSQL container.

How to level up

  • Mention Testcontainers with @DataJpaTest for testing against real database engines to catch dialect-specific issues.
  • Discuss @TestEntityManager as a test-friendly alternative to EntityManager with convenience methods like persistAndFlush.
  • Explain how to use @DataJpaTest with @Import to include custom JPA auditing configuration or converters.

Follow-up questions to expect

  • How do you use Testcontainers with @DataJpaTest?
  • How do you test custom @Query methods with @DataJpaTest?
  • What is the difference between @DataJpaTest and @SpringBootTest for repository testing?
Practice this question with AI feedback →
How are mock frameworks such as Mockito used in Spring Boot?
medium

What they're really asking

The interviewer wants to see if you can use Mockito effectively within Spring Boot's testing ecosystem for both unit and integration testing.

How you'll be scored

Weak

Has not used Mockito or only knows basic stubbing without verification or Spring integration.

Average

Can use when/thenReturn for stubbing but does not know about verification, argument captors, or @MockBean integration.

Strong

Demonstrates Mockito fluency including stubbing, verification, argument captors, BDD style, and integration with Spring Boot via @MockBean and @SpyBean.

How to structure your answer

  1. Explain Mockito's role in Spring Boot testing.
  2. Show stubbing with when/thenReturn.
  3. Show verification with verify.
  4. Demonstrate Spring Boot integration with @MockBean.

Key points to hit

  • Mockito is bundled in spring-boot-starter-test and is the default mock framework for creating test doubles.
  • Stubbing with when(mock.method()).thenReturn(value) defines return values, and thenThrow() simulates exception scenarios.
  • Verification with verify(mock).method() ensures the method was called with expected arguments and the right number of times.
  • @MockBean integrates Mockito mocks into the Spring application context, and @InjectMocks creates the class under test with mocks injected via constructor.

Common mistakes

  • Over-mocking by mocking every dependency including simple value objects, which makes tests brittle and hard to maintain.
  • Not using verify() to confirm that important interactions actually happened, leading to tests that pass even when the code under test does nothing.

Sample answer

Mockito is included in spring-boot-starter-test and I use it at two levels. In unit tests, I use @ExtendWith(MockitoExtension.class) and annotate dependencies with @Mock. I create the class under test with @InjectMocks, which injects the mocks via constructor. I stub behavior with when(orderRepository.findById(1L)).thenReturn(Optional.of(testOrder)) and verify interactions with verify(eventPublisher).publish(any(OrderCreatedEvent.class)).

For argument validation, I use ArgumentCaptor to capture what was passed to a mock and assert on it. In integration tests like @WebMvcTest, I use @MockBean to replace Spring-managed beans. The mock replaces the real bean in the context, so when MockMvc dispatches a request to the controller, it calls the mocked service.

I also use BDD-style methods like given() and then() from BDDMockito for more readable test code.

How to level up

  • Mention ArgumentCaptor for capturing and asserting on complex objects passed to mocked methods.
  • Discuss @Spy and @SpyBean for partial mocking when you want real behavior with selective method overrides.
  • Explain Mockito's strict stubbing mode (default in Mockito 4+) that fails tests with unnecessary stubbings to keep tests clean.

Follow-up questions to expect

  • What is the difference between a mock and a spy in Mockito?
  • How do you mock void methods in Mockito?
  • What is strict stubbing and why does Mockito enable it by default?
Practice this question with AI feedback →
When and where do you use @Transactional in testing?
medium

What they're really asking

This tests your understanding of transaction boundaries in testing and whether you know how @Transactional behavior differs between application code and test methods, particularly around rollback strategies.

How you'll be scored

Weak

Only mentions that @Transactional can be used in tests without understanding the automatic rollback behavior.

Average

Correctly explains that @Transactional on test methods causes automatic rollback but lacks details about when this is useful or problematic.

Strong

Demonstrates understanding of test transaction rollback, when to use @Commit or @Rollback annotations, and implications for testing transactional service methods.

How to structure your answer

  1. Explain @Transactional's default rollback behavior in test methods.
  2. Contrast with @Transactional in application code.
  3. Describe when automatic rollback helps vs hurts testing.
  4. Mention @Commit and @Rollback for controlling behavior.
  5. Address testing transactional service methods.

Key points to hit

  • Test methods annotated with @Transactional automatically roll back by default, unlike application code.
  • Use @Commit when you need to verify data persistence or test transaction propagation.
  • Be careful when testing @Transactional service methods as nested transactions can behave unexpectedly.
  • Consider using @Sql for data setup instead of relying on transaction rollback for cleanup.

Common mistakes

  • Assuming @Transactional behaves the same in tests as in application code.
  • Not understanding that automatic rollback can hide real transaction issues in your service layer.

Sample answer

In Spring Boot testing, @Transactional on test methods automatically rolls back at the end of each test, which is different from application code where transactions commit by default. This is useful for keeping tests isolated without manual cleanup, but I use @Commit when I need to test actual persistence or verify cascading operations work correctly.

When testing service methods that are themselves @Transactional, I'm careful about nested transaction behavior and sometimes use @Sql scripts instead to avoid transaction complexity that might mask real issues.

How to level up

  • Use @Transactional(propagation = Propagation.NOT_SUPPORTED) to test non-transactional behavior.
  • Combine with @TestTransaction programmatic control for complex transaction testing scenarios.
  • Consider TestEntityManager for JPA-specific transactional testing patterns.

Follow-up questions to expect

  • How would you test a method that requires multiple database commits?
  • What happens when you have nested @Transactional annotations in tests?
  • How do you verify that a service method properly handles transaction rollback on exceptions?
Practice this question with AI feedback →
What is the @DirtiesContext annotation and when do you use it?
medium

What they're really asking

This tests whether you understand Spring's ApplicationContext caching in tests and when context pollution requires forcing a context reload, which impacts test performance and isolation.

How you'll be scored

Weak

Vague mention of context clearing without understanding the performance implications or when it's actually needed.

Average

Correctly explains that @DirtiesContext forces context reload but doesn't articulate specific scenarios where it's necessary.

Strong

Demonstrates understanding of context caching, specific pollution scenarios, different DirtiesContext modes, and the performance trade-offs involved.

How to structure your answer

  1. Explain Spring's ApplicationContext caching between test methods.
  2. Define what context pollution means.
  3. Describe scenarios requiring @DirtiesContext.
  4. Mention different modes (BEFORE_METHOD, AFTER_METHOD, etc.)
  5. Address performance implications and alternatives.

Key points to hit

  • Spring caches ApplicationContext between tests for performance, but some tests pollute shared state.
  • Use @DirtiesContext when tests modify singleton beans, change system properties, or alter static state.
  • Available modes include AFTER_METHOD, AFTER_CLASS, and BEFORE_METHOD depending on when cleanup is needed.
  • Overuse kills test performance since context recreation is expensive, so prefer proper test isolation techniques.

Common mistakes

  • Using @DirtiesContext as a crutch instead of writing properly isolated tests.
  • Not understanding that it forces expensive context recreation for subsequent tests.

Sample answer

I use @DirtiesContext when a test modifies shared application state that could affect other tests, like changing system properties, modifying singleton beans, or altering static variables.

For example, if I'm testing a configuration that changes a bean's internal state or testing system property overrides, I'll use @DirtiesContext(methodMode = DirtiesContext.MethodMode.AFTER_METHOD) to force Spring to reload the context.

However, I try to avoid it when possible because context recreation is expensive and slows down the entire test suite, so I prefer using @MockBean or proper test data isolation instead.

How to level up

  • Use hierarchyMode to control whether parent contexts are also marked dirty in context hierarchies.
  • Combine with @TestPropertySource for property-based tests that need context isolation.
  • Consider @DirtiesContext at class level when multiple test methods in a class all pollute context.

Follow-up questions to expect

  • How would you refactor a test that currently needs @DirtiesContext to avoid context pollution?
  • What's the performance impact of @DirtiesContext in a large test suite?
  • When would you use @DirtiesContext at the class level versus method level?
Practice this question with AI feedback →
How do you perform integration testing with @SpringBootTest for a web application?
medium

What they're really asking

This tests your knowledge of full application context integration testing and whether you understand the different web environment modes and their appropriate use cases for realistic web layer testing.

How you'll be scored

Weak

Basic mention of @SpringBootTest without understanding web environment options or integration testing concepts.

Average

Knows about @SpringBootTest and mentions TestRestTemplate but lacks depth on web environment modes or testing strategy.

Strong

Demonstrates understanding of RANDOM_PORT vs MOCK vs DEFINED_PORT options, proper use of TestRestTemplate or WebTestClient, and integration testing best practices.

How to structure your answer

  1. Explain @SpringBootTest's role in full integration testing.
  2. Detail webEnvironment options (RANDOM_PORT, MOCK, DEFINED_PORT, NONE)
  3. Show TestRestTemplate or WebTestClient usage.
  4. Discuss testing strategy for different web layers.
  5. Address when to use integration vs slice tests.

Key points to hit

  • Use webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT for full server integration testing.
  • TestRestTemplate or WebTestClient provides HTTP client capabilities for testing actual HTTP endpoints.
  • RANDOM_PORT avoids port conflicts in CI environments while testing the full web stack.
  • Integration tests verify the complete request/response cycle including serialization, filters, and error handling.

Common mistakes

  • Using MOCK environment when you need to test actual HTTP behavior like headers or status codes.
  • Overusing integration tests when faster slice tests like @WebMvcTest would suffice.

Sample answer

For web integration testing, I use @SpringBootTest with webEnvironment = RANDOM_PORT to start the full application context with an embedded server on a random port. I inject TestRestTemplate to make actual HTTP requests to my endpoints, which tests the complete web stack including JSON serialization, exception handlers, and security filters.

For example, I'll test that a POST to /api/users returns 201 with the correct Location header and that validation errors return 400 with proper error responses. This differs from @WebMvcTest because it tests the entire application stack, not just the web layer in isolation.

How to level up

  • Use @LocalServerPort to inject the random port for custom HTTP client configurations.
  • Combine with @Sql for database-backed integration tests with realistic data scenarios.
  • Use WebTestClient with WebFlux applications for reactive testing patterns.

Follow-up questions to expect

  • When would you choose @SpringBootTest over @WebMvcTest for testing a REST controller?
  • How do you handle authentication in @SpringBootTest integration tests?
  • What's the difference between using TestRestTemplate and MockMvc for web testing?
Practice this question with AI feedback →

Ready to put this into practice?

Try these questions in a mock interview →

Still applying for jobs? Let Auto Apply do it

Spring Boot Testing (Advanced) (5)

What is the difference between @ContextConfiguration and @SpringBootTest?
hard

What they're really asking

This tests your deep understanding of Spring's test context configuration mechanisms and whether you know when to use low-level Spring testing features versus Spring Boot's opinionated testing approach.

How you'll be scored

Weak

Mentions both annotations exist but cannot explain the fundamental differences or use cases.

Average

Correctly identifies that @SpringBootTest is Spring Boot-specific but lacks depth on configuration loading differences.

Strong

Clearly explains that @ContextConfiguration is raw Spring testing while @SpringBootTest includes auto-configuration, and articulates when each is appropriate.

How to structure your answer

  1. Define @ContextConfiguration as core Spring testing annotation.
  2. Explain @SpringBootTest as Spring Boot extension with auto-configuration.
  3. Compare configuration loading mechanisms.
  4. Discuss when to use each approach.
  5. Address migration scenarios from Spring to Spring Boot.

Key points to hit

  • @ContextConfiguration manually specifies configuration classes or XML files without Spring Boot features.
  • @SpringBootTest automatically finds @SpringBootApplication and applies auto-configuration and property loading.
  • @ContextConfiguration gives fine-grained control over context composition in complex scenarios.
  • @SpringBootTest is preferred in Spring Boot applications for testing with realistic application context.

Common mistakes

  • Using @ContextConfiguration in Spring Boot applications when @SpringBootTest would provide better integration.
  • Not understanding that @ContextConfiguration bypasses Spring Boot's auto-configuration magic.

Sample answer

@ContextConfiguration is the core Spring Framework annotation for manually specifying which configuration classes or XML files to load in tests, giving you precise control over the application context. @SpringBootTest is Spring Boot's extension that automatically discovers your @SpringBootApplication class, applies all auto-configuration, loads application properties, and provides web environment options.

I use @ContextConfiguration when I need to test a specific configuration slice without Spring Boot overhead, like testing a standalone Spring configuration class. However, in Spring Boot applications, @SpringBootTest is usually better because it creates a context that matches your actual runtime environment.

How to level up

  • Use @ContextConfiguration with @EnableAutoConfiguration when you need Spring Boot features with custom configuration loading.
  • Combine @ContextConfiguration with @ActiveProfiles for testing specific configuration combinations.
  • Consider @ContextConfiguration for testing shared configuration modules that don't depend on Spring Boot.

Follow-up questions to expect

  • How would you test a configuration class that depends on Spring Boot auto-configuration?
  • Can you combine @ContextConfiguration and @SpringBootTest in the same test?
  • When migrating from Spring to Spring Boot, how do you update your test configurations?
Practice this question with AI feedback →
How do you use TestContainers for integration tests in Spring Boot?
hard

What they're really asking

This tests whether you understand modern integration testing practices using real external dependencies like databases, and your knowledge of containerized testing environments for production-like test scenarios.

How you'll be scored

Weak

Hasn't heard of TestContainers or only provides vague description without practical usage details.

Average

Knows TestContainers starts Docker containers but lacks specific Spring Boot integration knowledge or best practices.

Strong

Demonstrates practical experience with TestContainers lifecycle management, Spring Boot integration, and understands benefits over embedded databases for realistic testing.

How to structure your answer

  1. Explain TestContainers concept and Docker integration.
  2. Show Spring Boot integration with @Testcontainers annotation.
  3. Demonstrate container lifecycle management.
  4. Compare with embedded database approaches.
  5. Address performance and CI considerations.

Key points to hit

  • TestContainers starts real Docker containers for integration tests, providing production-like database behavior.
  • Use @Testcontainers and @Container annotations for automatic container lifecycle management.
  • Configure Spring Boot to connect to container database using dynamic properties or @DynamicPropertySource.
  • Provides better test fidelity than H2 embedded database for database-specific features and behaviors.

Common mistakes

  • Not properly managing container lifecycle leading to resource leaks or slow tests.
  • Using TestContainers for every test instead of reserving it for true integration scenarios.

Sample answer

I use TestContainers to start real Docker containers in integration tests, which gives me production-like database behavior that embedded databases can't match. I annotate my test class with @Testcontainers and create a @Container static field for a PostgreSQL container, then use @DynamicPropertySource to configure Spring Boot's datasource properties to point to the container.

This is especially valuable when testing database-specific features like JSON columns or custom functions that don't work in H2. The containers automatically start before tests and stop after, though I'm careful to use shared containers or container reuse for performance in large test suites.

How to level up

  • Use @Testcontainers(disabledWithoutDocker = true) to skip container tests when Docker isn't available.
  • Implement custom container configurations with network aliases for multi-service integration testing.
  • Leverage container reuse with Testcontainers.reuse.enable=true for faster test execution during development.

Follow-up questions to expect

  • How do you handle TestContainers performance in CI/CD pipelines?
  • What's your strategy for testing microservice interactions with TestContainers?
  • How do you manage TestContainers in a team environment where not everyone has Docker?
Practice this question with AI feedback →
How do you test microservices with contract testing (Spring Cloud Contract)?
hard

What they're really asking

This tests understanding of consumer-driven contract testing in microservices architectures. The interviewer wants to see if you can implement service contract verification that prevents breaking changes between services in production.

How you'll be scored

Weak

Gives a vague definition of contract testing without mentioning Spring Cloud Contract specifics or how it differs from integration testing.

Average

Explains Spring Cloud Contract basics and can describe producer/consumer contract flow but lacks implementation details.

Strong

Demonstrates hands-on experience with contract DSL, shows understanding of both producer and consumer testing phases, and explains how it fits into CI/CD pipelines.

How to structure your answer

  1. Define contract testing and its role in microservices.
  2. Explain Spring Cloud Contract's producer-consumer approach.
  3. Show concrete example of contract definition and testing.
  4. Discuss integration with build pipelines and versioning.
  5. Address common challenges and best practices.

Key points to hit

  • Spring Cloud Contract generates tests from contract definitions written in Groovy DSL or YAML.
  • Producer side generates MockMvc tests to verify contract compliance, consumer side gets WireMock stubs.
  • Contracts should be stored in producer's repository and versioned alongside the service.
  • Integration with Maven/Gradle plugins automates stub generation and publishing to artifact repository.

Common mistakes

  • Confusing contract testing with end-to-end integration testing or API documentation.
  • Not understanding that contracts are owned by consumers but verified by producers.

Sample answer

Spring Cloud Contract implements consumer-driven contract testing where consumers define expected API behavior in contracts, and producers verify they can fulfill those contracts. I write contracts using Groovy DSL defining request-response pairs, like a user service contract specifying that GET /users/123 returns specific JSON structure.

The framework generates MockMvc tests for the producer to verify compliance and creates WireMock stubs for consumers to test against. In our CI pipeline, we publish verified stubs to Nexus so consumer teams can run tests without depending on actual producer services, which prevents integration issues and allows independent deployment cycles.

How to level up

  • Use contract matchers for dynamic values like timestamps or IDs to make contracts more flexible.
  • Implement contract testing in stages, starting with critical service boundaries before expanding.
  • Consider using Spring Cloud Contract's messaging support for event-driven architectures.

Follow-up questions to expect

  • How do you handle contract versioning when breaking changes are necessary?
  • What's your strategy for testing contracts that involve authentication or complex business logic?
  • How do you ensure contract tests run fast enough for developer feedback loops?
Practice this question with AI feedback →
How do you test asynchronous operations in Spring Boot?
hard

What they're really asking

This tests knowledge of testing async operations like @Async methods, message processing, and reactive streams. The interviewer wants to see if you understand the timing and threading challenges unique to asynchronous code testing.

How you'll be scored

Weak

Suggests using Thread.sleep() or doesn't understand the difference between testing sync and async operations.

Average

Knows about CompletableFuture testing and basic async testing patterns but lacks depth on Spring-specific approaches.

Strong

Demonstrates understanding of @Async testing, TestExecutor configuration, and can handle complex scenarios like message queues and reactive streams testing.

How to structure your answer

  1. Identify the type of async operation being tested.
  2. Configure appropriate test execution context.
  3. Use proper waiting and assertion strategies.
  4. Handle timeouts and error scenarios.
  5. Verify threading behavior if relevant.

Key points to hit

  • @Async methods require @EnableAsync in test configuration and proper TaskExecutor setup for predictable testing.
  • Use CountDownLatch, Awaitility, or CompletableFuture.get() with timeouts instead of Thread.sleep()
  • For reactive streams, use StepVerifier from reactor-test for WebFlux applications.
  • @RabbitListener and @KafkaListener can be tested with @RabbitTest or @EmbeddedKafka annotations.

Common mistakes

  • Using Thread.sleep() which makes tests flaky and slow.
  • Not configuring async execution properly in tests, causing methods to run synchronously.

Sample answer

For @Async methods, I configure a TaskExecutor in my test context and use CountDownLatch or Awaitility to wait for completion. For example, when testing an async email service, I inject a CountDownLatch that the service decrements after sending, then await with a reasonable timeout.

For reactive code, I use StepVerifier to test WebFlux operations step by step, verifying both success and error scenarios. When testing message consumers like @RabbitListener, I use @EmbeddedBroker to create integration tests that verify the entire async flow without external dependencies.

How to level up

  • Create custom TestExecutor configurations that make async operations more predictable in tests.
  • Use @DirtiesContext when async operations might affect other tests through shared thread pools.
  • Consider using virtual time in reactive testing to speed up time-dependent operations.

Follow-up questions to expect

  • How do you test error handling in async operations, particularly when exceptions happen in background threads?
  • What's your approach to testing async operations that have complex retry or circuit breaker logic?
  • How do you ensure async tests don't create race conditions in your test suite?
Practice this question with AI feedback →
What is the difference between unit testing and integration testing in a Spring Boot context?
hard

What they're really asking

This tests understanding of test strategy and scope in Spring Boot applications. The interviewer wants to see if you can choose the right testing approach based on what you're validating and understand the trade-offs.

How you'll be scored

Weak

Gives generic definitions without relating to Spring Boot specifics or testing pyramid concepts.

Average

Understands basic differences and can mention @SpringBootTest vs @WebMvcTest but lacks nuance about when to use each.

Strong

Articulates clear testing strategy, understands Spring Boot's test slice annotations, and can explain trade-offs between speed, isolation, and confidence.

How to structure your answer

  1. Define unit testing scope in Spring Boot context.
  2. Explain integration testing levels and Spring Boot test slices.
  3. Compare speed, isolation, and confidence trade-offs.
  4. Provide concrete examples of when to use each approach.
  5. Discuss testing pyramid application to Spring Boot.

Key points to hit

  • Unit tests focus on single components without Spring context, using @MockBean or plain mocks for dependencies.
  • Integration tests in Spring Boot use test slices like @WebMvcTest, @DataJpaTest for focused integration or @SpringBootTest for full context.
  • Test slices provide faster integration tests by loading only relevant Spring configuration.
  • Integration tests verify component interactions and configuration while unit tests verify business logic in isolation.

Common mistakes

  • Using @SpringBootTest for everything, making tests slow and harder to maintain.
  • Writing unit tests that actually require Spring context, making them slow integration tests.

Sample answer

Unit tests in Spring Boot test individual components without Spring context, using plain JUnit and mocking frameworks. I test service classes by mocking their dependencies with @Mock annotations, focusing on business logic validation. Integration tests verify how components work together within Spring context.

I use test slices like @WebMvcTest for controller testing with MockMvc, or @DataJpaTest for repository testing with embedded database. These load only the necessary Spring configuration, running faster than full @SpringBootTest integration tests. The key is choosing the right scope for what you're validating while maintaining fast feedback loops.

How to level up

  • Use @TestConfiguration to customize Spring context for integration tests without affecting production configuration.
  • Create custom test slices for your application's specific layers when built-in slices don't fit.
  • Consider using @Testcontainers for integration tests that need real external dependencies like databases.

Follow-up questions to expect

  • How do you handle testing components that span multiple layers, like a service that calls both a repository and external API?
  • When would you choose @SpringBootTest over more focused test slices?
  • How do you maintain test performance as your application grows and more integration tests are added?
Practice this question with AI feedback →

Spring Boot Actuator & Monitoring (Beginner) (3)

What is Spring Boot Actuator?
easy

What they're really asking

This tests basic knowledge of Spring Boot's production-ready features. The interviewer wants to see if you understand monitoring and management capabilities beyond basic application functionality.

How you'll be scored

Weak

Gives vague answer about monitoring without mentioning specific endpoints or capabilities.

Average

Knows Actuator provides monitoring endpoints and can name a few like /health and /metrics.

Strong

Understands Actuator's role in production readiness, knows key endpoints, and mentions security considerations.

How to structure your answer

  1. Define Actuator's purpose in production applications.
  2. List key management and monitoring endpoints.
  3. Explain information provided by major endpoints.
  4. Mention security and customization aspects.
  5. Connect to production operations and monitoring.

Key points to hit

  • Actuator provides production-ready features like health checks, metrics, and application information.
  • Key endpoints include /health for readiness checks, /metrics for monitoring data, /info for application metadata.
  • Endpoints are HTTP-accessible for integration with monitoring systems like Prometheus or monitoring dashboards.
  • Security configuration is essential since endpoints expose sensitive application information.

Common mistakes

  • Not mentioning security implications of exposing management endpoints.
  • Thinking Actuator is only for debugging rather than production operations.

Sample answer

Spring Boot Actuator is a set of production-ready features that provide monitoring and management capabilities for Spring Boot applications. It exposes various HTTP endpoints like /actuator/health for application health status, /actuator/metrics for performance metrics, and /actuator/info for application information.

These endpoints help with monitoring application state, diagnosing issues, and integrating with operational tools like Prometheus for metrics collection. Actuator makes Spring Boot applications more observable and manageable in production environments, though you need to configure security properly since these endpoints can expose sensitive information.

How to level up

  • Customize health indicators to include business-specific health checks like database connectivity or external service availability.
  • Configure metrics export to monitoring systems like Micrometer registries for Prometheus, CloudWatch, or DataDog.
  • Use management.endpoints.web.exposure.include property to selectively expose only needed endpoints.

Follow-up questions to expect

  • How do you secure Actuator endpoints in production?
  • What custom health indicators have you implemented?
  • How do you integrate Actuator metrics with external monitoring systems?
Practice this question with AI feedback →
How do you enable Actuator in a Spring Boot application?
easy

What they're really asking

This tests basic configuration knowledge of Spring Boot Actuator. The interviewer wants to see if you understand the simple setup process and configuration options.

How you'll be scored

Weak

Doesn't know the dependency or basic configuration steps.

Average

Knows the spring-boot-starter-actuator dependency and basic property configuration.

Strong

Understands dependency setup, endpoint exposure configuration, and mentions security considerations for enabling Actuator.

How to structure your answer

  1. Add the Actuator starter dependency.
  2. Configure endpoint exposure in properties.
  3. Explain default vs custom endpoint availability.
  4. Mention security configuration needs.
  5. Show how to verify Actuator is working.

Key points to hit

  • Add spring-boot-starter-actuator dependency to Maven or Gradle build file.
  • Use management.endpoints.web.exposure.include property to specify which endpoints to expose.
  • By default, only /health endpoint is exposed over HTTP for security reasons.
  • Consider security implications when exposing endpoints, especially in production environments.

Common mistakes

  • Forgetting that most endpoints are not exposed by default and wondering why they're not accessible.
  • Enabling all endpoints in production without proper security configuration.

Sample answer

To enable Actuator, I add the spring-boot-starter-actuator dependency to my pom.xml or build.gradle file. By default, only the /health endpoint is exposed over HTTP. To expose additional endpoints, I configure management.endpoints.web.exposure.include in application.properties, setting it to specific endpoints like 'health,info,metrics' or '*' for all endpoints.

After starting the application, I can access endpoints at /actuator/health, /actuator/info, etc. In production, I always configure proper security since these endpoints can expose sensitive application information.

How to level up

  • Use management.endpoints.web.exposure.exclude to explicitly hide sensitive endpoints while exposing others.
  • Configure management.server.port to run Actuator on a separate port for network-level security.
  • Set up different exposure configurations for different Spring profiles (dev vs production)

Follow-up questions to expect

  • How do you configure Actuator to run on a different port than your main application?
  • What's your approach to exposing different Actuator endpoints in different environments?
  • How do you customize the /info endpoint to show application-specific information?
Practice this question with AI feedback →
What are the default endpoints provided by Actuator?
easy

What they're really asking

This tests whether you understand Spring Boot Actuator's out-of-the-box monitoring capabilities and can recognize production-ready features. The interviewer wants to see if you know what monitoring data is immediately available without custom development.

How you'll be scored

Weak

Lists only /health or gives vague answers without mentioning specific endpoint names.

Average

Names several key endpoints like /health, /info, /metrics but lacks understanding of their purposes.

Strong

Demonstrates knowledge of core endpoints and explains that most are disabled by default for security reasons.

How to structure your answer

  1. List the most commonly used default endpoints.
  2. Mention that most are disabled over HTTP by default.
  3. Explain the security reasoning behind this design.
  4. Note how to enable endpoints for monitoring.

Key points to hit

  • Key endpoints include /health, /info, /metrics, /env, /beans, /configprops.
  • Only /health and /info are exposed over HTTP by default for security.
  • All endpoints are available via JMX unless explicitly disabled.
  • Endpoints provide both operational visibility and debugging capabilities.

Common mistakes

  • Assuming all endpoints are exposed by default, which creates security vulnerabilities.
  • Not understanding the difference between JMX and HTTP exposure.

Sample answer

Actuator provides several default endpoints like /health for application status, /info for custom application information, /metrics for performance data, /env for environment properties, and /beans for Spring context details. However, only /health and /info are exposed over HTTP by default. The rest are available through JMX but disabled over HTTP for security reasons.

This follows Spring Boot's secure-by-default principle since endpoints like /env could expose sensitive configuration data.

How to level up

  • Explain the difference between management.endpoints.enabled-by-default and management.endpoints.web.exposure.include.
  • Mention that you can create custom endpoints by implementing the @Endpoint annotation.

Follow-up questions to expect

  • Which endpoints would you never expose in production and why?
  • How would you monitor a Spring Boot application in a Kubernetes environment?
  • What's the difference between management port and application port?
Practice this question with AI feedback →

Ready to put this into practice?

Try these questions in a mock interview →

Still applying for jobs? Let Auto Apply do it

Spring Boot Actuator & Monitoring (Intermediate) (5)

What are the actuator-provided endpoints used for monitoring (health, info, metrics, env, beans)?
medium

What they're really asking

This tests your understanding of production monitoring fundamentals and whether you can explain how each Actuator endpoint serves different operational needs. The interviewer wants to see if you understand monitoring strategy, not just endpoint names.

How you'll be scored

Weak

Can name endpoints but cannot explain their practical use cases or monitoring value.

Average

Explains basic functionality of each endpoint but misses the broader monitoring strategy.

Strong

Demonstrates how each endpoint fits into a comprehensive monitoring and troubleshooting workflow.

How to structure your answer

  1. Explain /health for application status and dependency checks.
  2. Describe /metrics for performance monitoring and alerting.
  3. Cover /info for application metadata and version tracking.
  4. Detail /env and /beans for configuration troubleshooting.

Key points to hit

  • /health provides readiness and liveness probes with custom health indicators.
  • /metrics exposes Micrometer data for APM tools like Prometheus or DataDog.
  • /info displays custom application metadata, build info, and Git commit details.
  • /env and /beans help debug configuration issues and Spring context problems.

Common mistakes

  • Using /health for detailed application metrics instead of simple up/down status.
  • Exposing /env in production without understanding it shows all environment variables including secrets.

Sample answer

The /health endpoint is crucial for load balancer health checks and shows the status of dependencies like databases or message queues. /metrics provides time-series data that monitoring tools like Prometheus scrape for performance dashboards and alerts. /info displays custom application metadata like version numbers and build timestamps, which helps during deployments. /env shows all configuration properties for debugging config issues, while /beans displays the entire Spring application context, which is invaluable when troubleshooting dependency injection problems.

How to level up

  • Implement custom HealthIndicator beans to check critical dependencies and fail fast.
  • Use /metrics with custom Micrometer counters and timers to track business-specific KPIs.
  • Configure /info to include Git commit info and build timestamps for deployment tracking.

Follow-up questions to expect

  • How would you implement a custom health indicator for a third-party API dependency?
  • What metrics would you expose for a high-traffic e-commerce application?
  • How do you handle sensitive data that might appear in /env?
Practice this question with AI feedback →
How do you enable or disable specific Actuator endpoints?
medium

What they're really asking

This tests your understanding of Actuator security configuration and production deployment practices. The interviewer wants to see if you can balance monitoring needs with security concerns.

How you'll be scored

Weak

Only knows about the include/exclude properties without understanding security implications.

Average

Can configure endpoint exposure but doesn't address security concerns or selective enabling.

Strong

Demonstrates understanding of security-first approach to endpoint management with specific configuration examples.

How to structure your answer

  1. Explain the default security posture (most endpoints disabled)
  2. Show how to enable specific endpoints using management.endpoints.web.exposure.include.
  3. Discuss selective enabling vs blanket exposure.
  4. Address security considerations for each endpoint type.

Key points to hit

  • Use management.endpoints.web.exposure.include to whitelist specific endpoints.
  • management.endpoints.web.exposure.exclude can blacklist endpoints from a broader include.
  • Consider using a separate management port for internal monitoring.
  • Different endpoints have different security implications and should be evaluated individually.

Common mistakes

  • Using management.endpoints.web.exposure.include=* in production without proper security.
  • Enabling debugging endpoints like /env or /configprops on public-facing applications.

Sample answer

I configure endpoint exposure using management.endpoints.web.exposure.include in application.properties, typically starting with just 'health,info,metrics' for production. For internal monitoring, I might add 'prometheus' for metrics scraping. I avoid using the wildcard '*' because endpoints like /env expose environment variables that could contain secrets.

For debugging in non-production environments, I selectively enable /beans or /configprops only when needed. I also configure a separate management port using management.server.port so monitoring endpoints aren't on the same port as the application.

How to level up

  • Use Spring profiles to have different endpoint configurations for different environments.
  • Consider using management.endpoints.web.base-path to change the default /actuator prefix for security through obscurity.

Follow-up questions to expect

  • How would you secure Actuator endpoints behind authentication?
  • What's your strategy for endpoint exposure in different environments (dev, staging, production)?
  • How do you handle Actuator endpoints in a microservices architecture?
Practice this question with AI feedback →
How do you secure Actuator endpoints?
medium

What they're really asking

This tests your understanding of production security practices for monitoring endpoints and whether you think about security implications from the start. The interviewer wants to see if you can implement monitoring without creating security vulnerabilities.

How you'll be scored

Weak

Suggests basic authentication or doesn't understand that endpoints can expose sensitive data.

Average

Knows about Spring Security integration but lacks depth on specific security configurations.

Strong

Demonstrates comprehensive security strategy including network isolation, authentication, and endpoint-specific access controls.

How to structure your answer

  1. Explain the principle of least privilege for endpoint access.
  2. Show Spring Security integration for authentication.
  3. Discuss network-level security (separate management port, internal networks)
  4. Cover endpoint-specific security considerations.

Key points to hit

  • Use Spring Security to require authentication for sensitive endpoints.
  • Configure management.server.port for network isolation.
  • Implement role-based access with different permissions for different endpoints.
  • Use management.endpoints.web.cors for cross-origin restrictions.

Common mistakes

  • Exposing all endpoints with basic authentication without considering data sensitivity.
  • Not understanding that some endpoints like /shutdown can modify application state.

Sample answer

I secure Actuator endpoints using multiple layers. First, I run them on a separate management port using management.server.port=8081, which allows network-level isolation behind a firewall. For authentication, I integrate with Spring Security and create specific roles like ACTUATOR_READ for monitoring tools and ACTUATOR_ADMIN for debugging access.

I configure endpoint-specific security in my SecurityConfig, allowing /health and /info to be public for load balancers, but requiring authentication for /metrics and /env. For highly sensitive endpoints like /env, I require ADMIN role and often disable them entirely in production.

How to level up

  • Implement custom authentication for monitoring tools using service accounts rather than user credentials.
  • Use Spring Security method-level security to control access to specific endpoint operations.
  • Consider using mutual TLS for service-to-service monitoring communication.

Follow-up questions to expect

  • How would you implement custom authentication for Prometheus to scrape metrics?
  • What's your approach to auditing access to sensitive Actuator endpoints?
  • How do you handle Actuator security in containerized environments?
Practice this question with AI feedback →
How do you check environment properties in your Spring Boot application?
medium

What they're really asking

This tests whether you understand different approaches to accessing configuration data and can choose the right method for different scenarios. The interviewer wants to see if you know both runtime inspection and development debugging techniques.

How you'll be scored

Weak

Only mentions application.properties file or basic @Value usage without understanding runtime inspection.

Average

Knows about /env endpoint but doesn't understand different methods or their appropriate use cases.

Strong

Demonstrates knowledge of multiple approaches and explains when to use each method for different scenarios.

How to structure your answer

  1. Explain the /env Actuator endpoint for runtime inspection.
  2. Mention @ConfigurationProperties for programmatic access.
  3. Discuss Environment bean injection for dynamic property access.
  4. Cover debugging techniques and security considerations.

Key points to hit

  • The /env endpoint shows all property sources and their values in JSON format.
  • Environment bean can be injected to programmatically access properties at runtime.
  • @ConfigurationProperties provides type-safe access to related configuration groups.
  • Property resolution follows Spring's precedence hierarchy (system props, env vars, application.properties)

Common mistakes

  • Exposing /env in production without understanding it shows sensitive data like database passwords.
  • Not understanding that /env shows resolved values, not the original property file format.

Sample answer

The primary way is through the /env Actuator endpoint, which shows all configuration properties from every source including application.properties, environment variables, and system properties in JSON format. This is great for debugging property resolution issues. For programmatic access, I can inject the Environment bean and call environment.getProperty() to check values at runtime.

If I need to inspect @ConfigurationProperties beans, the /configprops endpoint shows all bound configuration properties with their current values. However, I'm careful with /env in production since it exposes sensitive data like database passwords.

How to level up

  • Use /env/{propertyName} to query specific properties instead of dumping all configuration.
  • Implement custom PropertySource beans for complex configuration scenarios and verify they appear in /env.
  • Use @ConditionalOnProperty with /env to debug why certain beans aren't being created.

Follow-up questions to expect

  • How do you handle sensitive properties that shouldn't appear in /env?
  • What's the property resolution order in Spring Boot?
  • How would you debug a case where a property isn't being picked up correctly?
Practice this question with AI feedback →
How do you enable debug logging in a Spring Boot application?
medium

What they're really asking

This tests production readiness and debugging skills. The interviewer wants to see if you understand multiple approaches to enable debug logging and can adapt logging levels dynamically in production environments.

How you'll be scored

Weak

Only mentions application.properties with logging.level.root=DEBUG without understanding the performance impact.

Average

Shows multiple ways to enable debug logging but doesn't discuss selective logging or production concerns.

Strong

Demonstrates understanding of selective debug logging, runtime changes via Actuator, and performance implications in production.

How to structure your answer

  1. Explain configuration-based approaches.
  2. Show runtime modification options.
  3. Discuss selective vs global debug logging.
  4. Address production considerations.
  5. Mention monitoring impact.

Key points to hit

  • Multiple configuration methods (properties, YAML, environment variables)
  • Actuator loggers endpoint for runtime changes.
  • Package-specific logging levels to avoid performance issues.
  • Production safety and log volume management.

Common mistakes

  • Enabling root-level debug logging in production without considering performance impact.
  • Not knowing about runtime log level changes via Actuator endpoints.

Sample answer

There are several ways to enable debug logging in Spring Boot. For development, I typically set logging.level.com.mycompany=DEBUG in application.properties to target specific packages rather than enabling global debug logging. For production troubleshooting, I use the Actuator loggers endpoint to change log levels at runtime without restarting the application.

You can POST to /actuator/loggers/com.mycompany with the new log level. I avoid logging.level.root=DEBUG because it creates massive log volumes and performance overhead. Instead, I enable debug logging selectively for the components I'm investigating.

How to level up

  • Use conditional logging with slf4j's isDebugEnabled() to avoid expensive string operations when debug is disabled.
  • Set up log aggregation with structured logging (JSON format) to make debug information searchable.
  • Configure separate appenders for debug logs to isolate them from application logs.

Follow-up questions to expect

  • How do you handle log rotation and retention for debug logs?
  • What's the performance impact of debug logging on a high-traffic application?
  • How would you temporarily enable debug logging for a specific user session?
Practice this question with AI feedback →

Spring Boot Actuator & Monitoring (Advanced) (5)

How do you create custom Actuator endpoints?
hard

What they're really asking

This tests advanced Actuator knowledge and custom monitoring capabilities. The interviewer wants to see if you can extend Spring Boot's built-in observability with domain-specific endpoints.

How you'll be scored

Weak

Doesn't know how to create custom endpoints or confuses custom endpoints with regular REST controllers.

Average

Shows basic @Endpoint annotation usage but lacks understanding of different endpoint types or security considerations.

Strong

Demonstrates @Endpoint, @ReadOperation, @WriteOperation annotations with proper security configuration and explains when custom endpoints are appropriate.

How to structure your answer

  1. Explain @Endpoint annotation and component registration.
  2. Show @ReadOperation and @WriteOperation methods.
  3. Discuss endpoint security and exposure.
  4. Provide concrete business use case.
  5. Address testing and documentation.

Key points to hit

  • @Endpoint annotation with id parameter for endpoint identification.
  • @ReadOperation for GET operations and @WriteOperation for POST operations.
  • Endpoint security configuration and selective exposure (web, JMX)
  • Integration with existing Spring Security and management port configuration.

Common mistakes

  • Forgetting to expose custom endpoints in management.endpoints.web.exposure.include.
  • Not securing custom endpoints that might expose sensitive business data.

Sample answer

I create custom Actuator endpoints using the @Endpoint annotation with a unique id. For example, @Endpoint(id = 'business-metrics') creates an endpoint at /actuator/business-metrics. I use @ReadOperation for GET requests to expose read-only data like active user counts, and @WriteOperation for POST requests to trigger actions like cache clearing.

The endpoint class needs @Component annotation for Spring to discover it. I always configure management.endpoints.web.exposure.include to specifically include my custom endpoint, and I secure sensitive endpoints using the same patterns as other Actuator endpoints with proper authentication.

How to level up

  • Use @Selector parameters in operations to create dynamic endpoints like /actuator/cache/{cacheName}.
  • Implement custom health indicators instead of generic endpoints when checking system health.
  • Consider using @EndpointWebExtension to add web-specific functionality to existing endpoints.

Follow-up questions to expect

  • How do you secure custom endpoints differently from application endpoints?
  • What's the difference between custom endpoints and custom health indicators?
  • How do you version custom Actuator endpoints?
Practice this question with AI feedback →
How do you integrate Spring Boot Actuator with Prometheus and Grafana for monitoring?
hard

What they're really asking

This tests enterprise monitoring setup and production observability. The interviewer wants to see if you understand the complete monitoring pipeline from metrics collection to visualization.

How you'll be scored

Weak

Doesn't understand the relationship between Micrometer, Prometheus, and Grafana or how they work together.

Average

Shows basic Prometheus dependency and endpoint exposure but lacks understanding of metric types and dashboard creation.

Strong

Demonstrates complete integration including custom metrics, proper metric naming, Grafana dashboard creation, and alerting setup.

How to structure your answer

  1. Add Micrometer Prometheus dependency.
  2. Configure Prometheus scraping endpoint.
  3. Set up Prometheus server configuration.
  4. Create Grafana dashboards and data sources.
  5. Discuss custom metrics and alerting.

Key points to hit

  • Micrometer Prometheus registry dependency and automatic endpoint exposure.
  • Prometheus scraping configuration and service discovery.
  • Grafana data source configuration and dashboard creation.
  • Custom application metrics using MeterRegistry.

Common mistakes

  • Not understanding that Prometheus pulls metrics rather than Spring Boot pushing them.
  • Forgetting to configure proper metric retention and scraping intervals for production load.

Sample answer

I start by adding the micrometer-registry-prometheus dependency, which automatically exposes a /actuator/prometheus endpoint with metrics in Prometheus format. In the Prometheus server, I configure a scrape job pointing to my Spring Boot application's /actuator/prometheus endpoint. Then I set up Grafana with Prometheus as a data source and create dashboards using PromQL queries.

For custom business metrics, I inject MeterRegistry and create counters or timers like meterRegistry.counter('orders.processed'). I also set up alerting rules in Prometheus for critical metrics like error rates exceeding thresholds.

How to level up

  • Use metric tags consistently across your application to enable powerful filtering and grouping in Grafana.
  • Implement service discovery in Prometheus for dynamic environments using Kubernetes or Consul integration.
  • Create custom Micrometer binders for domain-specific metrics like database connection pools or message queue depths.

Follow-up questions to expect

  • How do you handle metric cardinality explosion with dynamic tags?
  • What's your approach to creating alerting rules for Spring Boot applications?
  • How do you monitor Spring Boot applications across multiple environments?
Practice this question with AI feedback →
What is Micrometer and how does it relate to Spring Boot Actuator?
hard

What they're really asking

This tests deep understanding of Spring Boot's metrics architecture. The interviewer wants to see if you understand the abstraction layer that makes Spring Boot monitoring vendor-agnostic.

How you'll be scored

Weak

Confuses Micrometer with Actuator or doesn't understand the vendor-neutral metrics abstraction concept.

Average

Knows Micrometer is a metrics facade but doesn't explain the registry concept or integration benefits.

Strong

Explains Micrometer as a vendor-neutral metrics facade, demonstrates registry switching, and shows custom metrics creation.

How to structure your answer

  1. Define Micrometer as metrics abstraction layer.
  2. Explain relationship to Actuator endpoints.
  3. Show registry switching capabilities.
  4. Demonstrate custom metrics creation.
  5. Discuss production benefits.

Key points to hit

  • Micrometer provides vendor-neutral metrics API similar to SLF4J for logging.
  • Spring Boot Actuator uses Micrometer internally for all metrics collection.
  • Registry implementations for different monitoring systems (Prometheus, DataDog, CloudWatch)
  • MeterRegistry injection for custom application metrics.

Common mistakes

  • Thinking Micrometer and Actuator are competing technologies rather than complementary.
  • Not understanding that switching monitoring backends only requires dependency changes with Micrometer.

Sample answer

Micrometer is a vendor-neutral metrics collection facade for Spring Boot, similar to how SLF4J works for logging. Spring Boot Actuator uses Micrometer internally to collect all JVM, HTTP, and database metrics.

The key benefit is that I can switch between monitoring systems like Prometheus, DataDog, or CloudWatch by just changing the Micrometer registry dependency without changing application code. I inject MeterRegistry to create custom metrics like Timer.Sample timer = Timer.start(meterRegistry) for measuring business operations.

This abstraction means my metrics collection code stays the same regardless of which monitoring backend I choose.

How to level up

  • Use Micrometer's @Timed annotation for automatic method timing instead of manual timer creation.
  • Configure different meter registries for different environments (dev uses simple registry, prod uses Prometheus)
  • Leverage Micrometer's built-in meter binders for technologies like Redis, MongoDB, and message queues.

Follow-up questions to expect

  • How do you create composite meter registries for multiple monitoring systems?
  • What are the performance implications of different Micrometer registries?
  • How do you test custom metrics created with Micrometer?
Practice this question with AI feedback →
How do you monitor JVM metrics, thread pools, and database connections with Actuator?
hard

What they're really asking

This tests comprehensive production monitoring knowledge. The interviewer wants to see if you understand the full observability stack and can monitor critical application infrastructure components.

How you'll be scored

Weak

Only knows about basic JVM metrics without understanding database connection monitoring or thread pool visibility.

Average

Shows awareness of multiple metric types but lacks specific configuration knowledge or custom monitoring setup.

Strong

Demonstrates detailed knowledge of HikariCP metrics, thread pool monitoring, custom MBeans, and proactive alerting strategies.

How to structure your answer

  1. Show JVM metrics configuration and key indicators.
  2. Explain database connection pool monitoring.
  3. Detail thread pool metrics collection.
  4. Discuss custom MBean exposure.
  5. Address alerting thresholds and strategies.

Key points to hit

  • Built-in JVM metrics including heap, non-heap, and GC metrics.
  • HikariCP connection pool metrics for database monitoring.
  • Thread pool metrics from TaskExecutor implementations.
  • Custom MBean registration for application-specific monitoring.

Common mistakes

  • Not monitoring database connection pool exhaustion which causes production outages.
  • Ignoring thread pool queue sizes which indicate processing bottlenecks.

Sample answer

Actuator automatically exposes JVM metrics like heap usage, GC activity, and thread counts through the /actuator/metrics endpoint. For database connections, I enable HikariCP metrics with spring.datasource.hikari.register-mbeans=true to monitor active connections, pool size, and connection wait times. Thread pool monitoring works automatically with Spring's @Async TaskExecutor, showing queue sizes and active threads.

I also register custom MBeans for business-specific metrics and use MeterRegistry to create gauges for real-time monitoring. These metrics feed into Grafana dashboards with alerts for connection pool exhaustion and thread pool saturation.

How to level up

  • Set up alerts for leading indicators like connection pool usage above 80% rather than waiting for exhaustion.
  • Monitor GC pause times and frequency to detect memory pressure before OutOfMemoryError occurs.
  • Use custom health indicators that combine multiple metrics to create meaningful business health checks.

Follow-up questions to expect

  • How do you correlate JVM metrics with application performance degradation?
  • What are the key database connection pool metrics that predict outages?
  • How do you monitor distributed transactions across multiple Spring Boot services?
Practice this question with AI feedback →
How do you implement health indicators for custom components?
hard

What they're really asking

This tests whether you understand Spring Boot Actuator's extensibility and can implement production-ready health monitoring for custom business components, not just infrastructure.

How you'll be scored

Weak

Only knows about built-in health indicators or gives vague answers about 'checking if things work'.

Average

Can implement a basic HealthIndicator interface but doesn't consider edge cases or meaningful health metrics.

Strong

Demonstrates understanding of HealthIndicator lifecycle, proper status reporting, and integration with monitoring systems.

How to structure your answer

  1. Explain the HealthIndicator interface and its purpose.
  2. Show a concrete implementation example.
  3. Discuss health status types and when to use each.
  4. Cover registration and configuration.
  5. Address monitoring integration concerns.

Key points to hit

  • HealthIndicator interface requires implementing health() method returning Health object.
  • Health.Builder provides status (UP, DOWN, OUT_OF_SERVICE) and details for debugging.
  • Custom health indicators auto-register when annotated with @Component.
  • Consider async health checks for external dependencies to avoid blocking main thread.

Common mistakes

  • Making health checks too expensive or slow, blocking application startup.
  • Returning UP status when component is actually degraded but functional.

Sample answer

I implement custom health indicators by creating a class that implements the HealthIndicator interface and overrides the health() method. For example, if I have a Redis cache component, I'd create a RedisHealthIndicator that attempts a simple ping operation and returns Health.up().withDetail('redis.version', version) for success or Health.down().withException(ex) for failures.

The key is making the check lightweight and meaningful. I register it as a @Component so Spring Boot automatically includes it in the /actuator/health endpoint. For external services, I often use circuit breaker patterns to avoid cascading failures when the health check itself times out.

How to level up

  • Implement ReactiveHealthIndicator for non-blocking health checks in reactive applications.
  • Use Health.Builder.withDetails() to provide actionable debugging information for operations teams.
  • Consider implementing custom HealthIndicatorRegistry for dynamic health indicator management.

Follow-up questions to expect

  • How would you handle a scenario where a health check needs to be disabled temporarily?
  • What's the difference between Health.DOWN and Health.OUT_OF_SERVICE?
  • How do you secure sensitive information in health indicator details?
Practice this question with AI feedback →

Ready to put this into practice?

Try these questions in a mock interview →

Still applying for jobs? Let Auto Apply do it

Spring AOP (Beginner) (3)

What is Aspect-Oriented Programming (AOP)?
easy

What they're really asking

This tests basic understanding of AOP concepts and whether you can articulate how cross-cutting concerns are separated from business logic in Spring applications.

How you'll be scored

Weak

Cannot explain what cross-cutting concerns are or gives completely incorrect definition.

Average

Knows AOP handles cross-cutting concerns but can't give concrete examples or explain benefits.

Strong

Clearly explains AOP purpose, provides relevant examples like logging or security, and understands when to use it.

How to structure your answer

  1. Define AOP and its core purpose.
  2. Explain cross-cutting concerns with examples.
  3. Describe how AOP separates concerns from business logic.
  4. Mention key AOP concepts briefly.
  5. Give Spring-specific context.

Key points to hit

  • AOP addresses cross-cutting concerns that span multiple classes like logging, security, and transactions.
  • Allows separation of business logic from infrastructure concerns.
  • Spring AOP uses proxy-based approach for method interception.
  • Common use cases include @Transactional, @Cacheable, and custom logging aspects.

Common mistakes

  • Confusing AOP with dependency injection.
  • Thinking AOP can intercept private methods or final classes in Spring's proxy-based implementation.

Sample answer

Aspect-Oriented Programming is a programming paradigm that handles cross-cutting concerns, which are functionalities that span across multiple classes like logging, security, or transaction management. Instead of scattering this code throughout your business logic, AOP lets you define these concerns separately as aspects and apply them declaratively.

For example, rather than adding logging code to every method, I can create a logging aspect that automatically logs method entry and exit. Spring AOP makes this seamless with annotations like @Transactional, where the transaction management code is completely separated from my business methods but still applied at runtime through proxies.

How to level up

  • Understand the difference between Spring AOP (proxy-based) and AspectJ (bytecode weaving) for choosing the right approach.
  • Learn to combine multiple aspects and understand their execution order using @Order annotation.

Follow-up questions to expect

  • What are the limitations of Spring AOP compared to full AspectJ?
  • How does Spring implement AOP under the hood?
  • Can you give an example of when NOT to use AOP?
Practice this question with AI feedback →
What is a JoinPoint?
easy

What they're really asking

This tests understanding of AOP terminology and whether you know the specific points where aspect logic can be applied in method execution flow.

How you'll be scored

Weak

Cannot define JoinPoint or confuses it with other AOP concepts.

Average

Knows JoinPoint is where aspects are applied but lacks detail about types or context.

Strong

Clearly explains JoinPoint as execution points and understands different types like method calls, field access, etc.

How to structure your answer

  1. Define what a JoinPoint represents.
  2. Explain it as points in program execution.
  3. List common types of JoinPoints.
  4. Connect to Spring AOP limitations.
  5. Give practical example.

Key points to hit

  • JoinPoint represents a point in program execution where an aspect can be applied.
  • Common types include method calls, method executions, field access, and exception handling.
  • In Spring AOP, JoinPoints are limited to method executions on Spring beans.
  • JoinPoint interface provides runtime information about the intercepted method.

Common mistakes

  • Thinking Spring AOP supports all JoinPoint types (it only supports method execution)
  • Confusing JoinPoint with Pointcut (JoinPoint is the actual execution point, Pointcut is the expression that selects JoinPoints)

Sample answer

A JoinPoint is a specific point during program execution where an aspect can be applied, like when a method is called, a field is accessed, or an exception is thrown. Think of it as a hook in your code where cross-cutting logic can be inserted.

In Spring AOP, JoinPoints are limited to method executions on Spring-managed beans, so I can intercept when methods start or finish but not field access or constructor calls. When I write an aspect method, the JoinPoint parameter gives me runtime information about the intercepted method, like its arguments, target object, and method signature.

How to level up

  • Use ProceedingJoinPoint in @Around advice to control method execution flow.
  • Access method annotations through JoinPoint.getSignature() for metadata-driven aspects.

Follow-up questions to expect

  • What's the difference between JoinPoint and ProceedingJoinPoint?
  • How do you access method arguments from a JoinPoint?
  • What JoinPoint types does full AspectJ support that Spring AOP doesn't?
Practice this question with AI feedback →
What is an Advice and what are its types?
easy

What they're really asking

This tests knowledge of AOP advice types and understanding of when different types of aspect logic should execute relative to the target method.

How you'll be scored

Weak

Cannot define advice or only knows one type without understanding execution timing.

Average

Lists some advice types but unclear about when each executes or their use cases.

Strong

Clearly explains all advice types with correct execution timing and provides appropriate use case examples.

How to structure your answer

  1. Define what advice is in AOP context.
  2. List the five advice types.
  3. Explain execution timing for each type.
  4. Provide use case examples.
  5. Mention Spring-specific annotations.

Key points to hit

  • Advice is the actual code that runs at a JoinPoint when an aspect is triggered.
  • Five types: @Before, @After, @AfterReturning, @AfterThrowing, and @Around.
  • @Around advice is most powerful as it can control method execution and modify parameters/return values.
  • Each advice type serves different cross-cutting concern needs like logging, security, or error handling.

Common mistakes

  • Using @After when you need @AfterReturning (After runs regardless of success/failure)
  • Not understanding that @Around advice must call ProceedingJoinPoint.proceed() to continue execution.

Sample answer

Advice is the actual code that executes when an aspect is triggered at a JoinPoint.

There are five types: @Before runs before the target method, useful for validation or logging entry. @AfterReturning executes only after successful completion, good for success logging or result processing. @AfterThrowing runs when exceptions occur, perfect for error handling. @After always executes regardless of success or failure, like a finally block. @Around is the most powerful because it wraps the entire method execution, letting me modify parameters, control whether the method runs, and transform return values.

For example, I use @Around for caching where I might return cached data without calling the actual method.

How to level up

  • Combine multiple advice types in the same aspect for comprehensive monitoring.
  • Use @Around advice order carefully with other aspects to avoid unexpected behavior.
  • Leverage advice method parameters to access JoinPoint metadata efficiently.

Follow-up questions to expect

  • How do you handle exceptions in @Around advice?
  • Can multiple advice of the same type apply to one method?
  • What happens if @Before advice throws an exception?
Practice this question with AI feedback →

Spring AOP (Intermediate) (4)

What is an Aspect?
medium

What they're really asking

This tests understanding of how individual advice methods are organized into cohesive units and whether you grasp aspect modularity and reusability concepts.

How you'll be scored

Weak

Confuses aspect with advice or cannot explain how aspects organize cross-cutting concerns.

Average

Knows aspect contains advice but doesn't understand pointcut expressions or aspect structure.

Strong

Clearly explains aspect as a module containing advice and pointcuts, understands @Aspect annotation and aspect lifecycle.

How to structure your answer

  1. Define aspect as a modular unit.
  2. Explain relationship between aspect, advice, and pointcuts.
  3. Show aspect structure with annotations.
  4. Discuss aspect instantiation and lifecycle.
  5. Connect to real-world examples.

Key points to hit

  • Aspect is a class that modularizes cross-cutting concerns by combining advice methods and pointcut expressions.
  • Marked with @Aspect annotation and typically also @Component for Spring management.
  • Contains one or more advice methods (@Before, @After, etc.) and defines where they apply using pointcut expressions.
  • Aspects are singleton by default in Spring, sharing state across all advised methods.

Common mistakes

  • Forgetting @Component annotation, making the aspect invisible to Spring.
  • Storing mutable state in aspect fields without considering thread safety.

Sample answer

An aspect is a class that modularizes a cross-cutting concern by bundling together the advice methods and pointcut expressions that define where and when the advice should run.

I create an aspect by annotating a class with @Aspect and @Component, then define advice methods like @Before or @Around along with pointcut expressions that specify which methods should be intercepted. For example, my LoggingAspect might contain a @Before advice that logs method entry for all service layer methods.

The aspect acts as a container that keeps related cross-cutting logic organized and reusable. Spring instantiates aspects as singletons, so they can be applied across multiple target objects.

How to level up

  • Use @Pointcut methods to define reusable pointcut expressions across multiple advice methods.
  • Consider aspect instantiation models like perthis() or pertarget() for stateful aspects.
  • Organize related aspects into separate classes for better maintainability and testing.

Follow-up questions to expect

  • How do you define reusable pointcut expressions?
  • What are the different aspect instantiation models in Spring?
  • How do you test aspects in isolation?
Practice this question with AI feedback →
What is a Pointcut?
medium

What they're really asking

This tests your understanding of AOP terminology and how pointcuts enable precise aspect targeting. The interviewer wants to see if you can explain how pointcuts work beyond just definitions and understand their role in production AOP implementations.

How you'll be scored

Weak

Gives a vague definition without explaining how pointcuts actually select join points or their syntax.

Average

Correctly defines pointcuts as expressions that match join points with a basic example.

Strong

Demonstrates understanding of pointcut expressions, different designators, and how they impact performance and maintainability in real applications.

How to structure your answer

  1. Define what a pointcut is in AOP context.
  2. Explain how pointcuts select join points.
  3. Show concrete pointcut expression syntax.
  4. Discuss precision and performance implications.
  5. Mention common pointcut designators.

Key points to hit

  • Pointcuts are expressions that define where aspects should be applied by matching join points.
  • Spring AOP uses AspectJ pointcut expression language with designators like execution(), within(), @annotation()
  • More specific pointcuts improve performance by reducing unnecessary proxy creation.
  • Pointcuts can be combined using logical operators (&&, ||, !) for precise targeting.

Common mistakes

  • Confusing pointcuts with join points or advice.
  • Not understanding that overly broad pointcuts can impact application performance.

Sample answer

A pointcut is an expression that defines where an aspect should be applied by selecting specific join points in your code. It's like a filter that matches method executions, field access, or other program execution points. For example, execution(* com.myapp.service.*.*(..)) matches all method executions in service classes.

The key is being precise because broad pointcuts can hurt performance by creating unnecessary proxies. Spring AOP supports AspectJ pointcut expressions, so you can use designators like @annotation() to target methods with specific annotations, or within() to target entire packages.

How to level up

  • Use @annotation() pointcuts with custom annotations for cleaner, more maintainable aspect targeting.
  • Combine multiple pointcut designators with logical operators for precise control without performance overhead.
  • Consider using named pointcuts with @Pointcut annotation to reuse complex expressions across multiple advice methods.

Follow-up questions to expect

  • Can you show me how to write a pointcut that targets only public methods in service classes that are annotated with @Transactional?
  • What's the performance difference between using execution() versus @annotation() pointcuts?
  • How would you debug a pointcut that's not matching the methods you expect?
Practice this question with AI feedback →
What is Weaving and when does it happen?
medium

What they're really asking

This tests your understanding of how AOP aspects are actually integrated into application code and the different weaving strategies available. The interviewer wants to know if you understand the technical implementation details that affect performance and deployment.

How you'll be scored

Weak

Provides a basic definition without explaining when weaving occurs or different weaving types.

Average

Correctly explains weaving as aspect integration with mention of compile-time and runtime options.

Strong

Demonstrates knowledge of different weaving strategies, their trade-offs, and how Spring AOP specifically implements runtime weaving through proxies.

How to structure your answer

  1. Define weaving as the process of integrating aspects into target code.
  2. Explain the three main weaving times.
  3. Focus on Spring AOP's runtime weaving approach.
  4. Discuss proxy-based implementation details.
  5. Mention performance and design implications.

Key points to hit

  • Weaving is the process of applying aspects to target objects to create advised objects.
  • Three types: compile-time, post-compile (binary), and runtime weaving.
  • Spring AOP uses runtime weaving through JDK dynamic proxies or CGLIB proxies.
  • Runtime weaving offers flexibility but adds slight performance overhead compared to compile-time weaving.

Common mistakes

  • Assuming Spring AOP uses compile-time weaving like full AspectJ.
  • Not understanding that proxy-based weaving means self-calls within a class bypass aspects.

Sample answer

Weaving is the process where aspects are integrated with your target objects to create the final advised objects. In Spring AOP, this happens at runtime through proxy creation. When Spring creates a bean that has aspects applied to it, it generates either a JDK dynamic proxy for interfaces or a CGLIB proxy for concrete classes.

This means the weaving occurs when the application context starts up and beans are instantiated. Unlike AspectJ's compile-time weaving, Spring's runtime approach gives you flexibility to modify aspects without recompilation, but it does mean there's a slight performance cost and self-calls within a class won't trigger aspects.

How to level up

  • Use @EnableLoadTimeWeaving with AspectJ for true load-time weaving when you need to intercept self-calls or work with final classes.
  • Consider the proxy implications when designing services - external calls go through proxies, internal calls don't.
  • Profile proxy creation overhead in high-throughput applications where bean creation happens frequently.

Follow-up questions to expect

  • Why don't aspects work on self-calls within the same class in Spring AOP?
  • When would you choose AspectJ's compile-time weaving over Spring AOP's runtime weaving?
  • How can you verify that weaving has occurred correctly for a particular bean?
Practice this question with AI feedback →
What is the difference between concern and cross-cutting concern?
medium

What they're really asking

This tests whether you understand the fundamental problem AOP solves by distinguishing between business logic and infrastructure concerns. The interviewer wants to see if you can identify when AOP is the right solution versus when it adds unnecessary complexity.

How you'll be scored

Weak

Gives vague definitions without concrete examples or understanding of why the distinction matters.

Average

Correctly distinguishes concerns from cross-cutting concerns with basic examples like logging or security.

Strong

Demonstrates understanding of how cross-cutting concerns create code duplication and maintenance issues, with specific examples of when AOP is or isn't the right solution.

How to structure your answer

  1. Define concern as a specific functionality or responsibility.
  2. Explain cross-cutting concern as functionality that spans multiple modules.
  3. Provide concrete examples of each type.
  4. Discuss why cross-cutting concerns are problematic without AOP.
  5. Mention when AOP is and isn't the right solution.

Key points to hit

  • A concern is a specific piece of functionality like user authentication or order processing.
  • Cross-cutting concerns span multiple modules like logging, security, transaction management, or caching.
  • Cross-cutting concerns lead to code duplication and tight coupling when implemented traditionally.
  • AOP solves cross-cutting concerns by centralizing them into reusable aspects.

Common mistakes

  • Using AOP for concerns that belong in the main business logic flow rather than true cross-cutting functionality.
  • Not recognizing that some cross-cutting concerns are better handled by framework features than custom aspects.

Sample answer

A concern is a specific piece of functionality your application needs to handle, like processing payments or managing user accounts. A cross-cutting concern is functionality that cuts across multiple parts of your application, like logging, security, or transaction management.

For example, you might need to log method entry and exit in your service layer, repository layer, and controller layer. Without AOP, you'd duplicate that logging code everywhere, making it hard to maintain and change. Cross-cutting concerns create tangled code because they're scattered throughout your application.

AOP lets you centralize these concerns into aspects, so your business logic stays clean and focused.

How to level up

  • Identify cross-cutting concerns by looking for repeated patterns across unrelated classes - that's usually a sign AOP could help.
  • Not every cross-cutting concern needs AOP - sometimes framework features like Spring's @Transactional are better than custom aspects.
  • Use AOP for concerns that are truly orthogonal to business logic, avoid it for concerns that are part of the core workflow.

Follow-up questions to expect

  • Can you give me an example of a concern that might seem cross-cutting but shouldn't be handled with AOP?
  • How would you decide between using AOP versus a decorator pattern for a cross-cutting concern?
  • What cross-cutting concerns have you implemented using AOP in production applications?
Practice this question with AI feedback →

Ready to put this into practice?

Try these questions in a mock interview →

Still applying for jobs? Let Auto Apply do it

Frequently Asked Questions

What Spring Boot topics come up most in interviews?
Dependency injection, bean lifecycle, REST controller design, and Spring Data JPA are the most frequently tested areas. Senior-level interviews also cover auto-configuration internals, security filters, and microservice patterns like circuit breakers and service discovery.
Do I need to know core Spring Framework or just Spring Boot?
You need both. Spring Boot simplifies configuration, but interviewers expect you to understand what it automates. Questions about IoC containers, bean scopes, and AOP proxies test core Spring knowledge that Boot abstracts away. Knowing the fundamentals helps you debug issues that auto-configuration cannot solve.
How should I prepare for Spring Boot coding questions?
Build a small REST API from scratch with Spring Boot, including CRUD endpoints, validation, error handling, and database integration. Practice explaining your design decisions out loud. Interviewers care as much about your reasoning as your code.
Are Spring Boot interview questions different for microservices roles?
Yes. Microservices roles add questions about service discovery with Eureka, API gateways, circuit breakers with Resilience4j, distributed tracing, and inter-service communication patterns. You should also be ready to discuss when microservices are appropriate versus a monolithic approach.
What version of Spring Boot should I study?
Focus on Spring Boot 3.x, which requires Java 17+ and uses Jakarta EE namespaces instead of javax. Interviewers notice when candidates reference outdated APIs. Understanding the migration from Boot 2.x to 3.x is also a valuable talking point.
How can I practice Spring Boot interview questions effectively?
Start by reviewing each question and answering it out loud before checking references. Then build small projects that exercise the concepts. AI mock interviews let you practice explaining Spring Boot topics under realistic pressure with follow-up questions.

Stop Preparing in Your Head. Start Practicing Out Loud.

Drop your resume, add a job description, and get a mock interview like the real thing.

Start Free Mock Interview →
No credit card required. 5 free credits to start.

Still applying for jobs? Let Auto Apply do it for you.

Try Auto Apply →