These Spring Boot interview questions cover auto-configuration, starters, web applications, configuration, testing and operational endpoints. Focus on why Boot creates a bean, when its defaults back off and how you would verify the effective configuration. The answers explain both the default behavior and how to inspect or change it.
1. What does Spring Boot add to Spring Framework?
Spring Framework provides the container, dependency injection and web and data programming models. Spring Boot adds managed dependencies, conditional auto-configuration, executable packaging and operational features so an application needs less initial setup.
Spring Framework: components and programming model
Spring Boot: starters + conditions + executable application
A starter supplies libraries for a feature. Auto-configuration examines the classpath, properties and existing beans before contributing defaults. The application can provide its own bean or property when the default does not fit. Adding a dependency alone does not guarantee that every associated feature becomes active.
2. What happens when a Spring Boot application starts?
SpringApplication.run prepares the environment, creates the application context, registers beans, and starts an embedded web server when the application is a servlet or reactive web application. Auto-configuration contributes beans only when its conditions match.
configuration and classpath -> condition evaluation -> application context
-> web server, if applicable
If a bean is missing, inspect the condition evaluation report before adding more annotations. The report shows which auto-configuration candidates matched and why others did not.
3. What are the benefits and tradeoffs of Spring Boot?
Boot reduces repetitive configuration and gives a tested dependency baseline. Executable packaging and Actuator support can simplify deployment and inspection. The tradeoff is that a starter may bring dependencies an application does not use, and conditional defaults can be surprising until the team inspects the effective configuration.
add starter -> inspect dependency tree -> inspect condition report
-> keep defaults or override a specific bean/property
Use the dependency tree for packaging or conflict questions. Use the condition evaluation report when a bean appears unexpectedly or a default does not appear.
4. How do you start a Spring Boot Maven project?
Generate a Maven project with Spring Initializr, select the features the application needs, and inspect the resulting pom.xml. The generated parent or dependency-management configuration pins a coherent dependency set. Keep that version explicit in the project, and update it as a planned change.
Initializr -> pom.xml and source tree -> add feature code
-> mvn spring-boot:run -> inspect startup result
For a Spring MVC API, select the web starter offered by the current Initializr. The Spring Boot first-application guide shows the current Maven layout and starter name.
5. How does auto-configuration decide whether to create a bean?
Auto-configuration evaluates conditions such as the presence of a class, property value or existing bean. A user-defined bean can cause an auto-configured default to back off. This is conditional configuration, not a scan that blindly creates a bean for every library.
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
class Application {}
The example excludes one auto-configuration when the application does not want Boot to configure a data source. Before excluding anything, start the app with --debug and read the condition evaluation report to see what matched and why. The internals of an auto-configuration class are not a stable customization API.
6. What does a Spring Boot starter provide?
A starter is a dependency descriptor for a common application feature. It pulls in a selected set of libraries; Boot’s dependency management chooses compatible versions. A starter is not itself a promise that every bean in those libraries will be enabled.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc</artifactId>
</dependency>
This web starter provides the dependencies for a Spring MVC application. Check the current web reference and the dependency tree if the project uses a different web stack or excludes a transitive dependency.
7. Which annotations start a Boot application?
@SpringBootApplication marks the main configuration class and combines configuration, component scanning and auto-configuration. Place it in a package above the application’s components so the default scan finds them.
@SpringBootApplication
class ShopApplication {
public static void main(String[] args) {
SpringApplication.run(ShopApplication.class, args);
}
}
@Configuration and @Bean declare individual configuration. Conditional annotations such as @ConditionalOnMissingBean are mainly useful when building reusable auto-configuration. They are not required on every application class.
8. How do you expose a REST endpoint?
Add the current Spring MVC web starter, then declare a controller method with a request mapping. A @RestController writes the return value to the HTTP response through a message converter.
@RestController
class GreetingController {
@GetMapping("/greetings/{name}")
Greeting greeting(@PathVariable String name) {
return new Greeting("Hello, " + name);
}
}
record Greeting(String message) {}
A GET request to /greetings/Ada returns an object whose message is Hello, Ada; with a JSON converter, the response body is JSON. Keep persistence and business decisions in a service when the endpoint grows beyond this small example.
9. How do @Controller and @RestController differ?
A @Controller can return a view name for server-side rendering. @RestController combines @Controller with @ResponseBody, so handler return values are written to the response body. The actual media type depends on the return value and available converters.
@Controller
class PageController {
@GetMapping("/home")
String home() { return "home"; }
}
@RestController
class StatusController {
@GetMapping("/status")
Map<String, String> status() { return Map.of("state", "ok"); }
}
The first method selects a view named home. The second writes a response body, commonly JSON when a JSON converter is present.
10. How do @RequestMapping and @GetMapping differ?
@RequestMapping can map a path and specify an HTTP method. @GetMapping is a composed annotation for GET requests. Choose the shortcut when it expresses the method clearly.
@GetMapping("/orders")
List<Order> orders() { return service.list(); }
// Equivalent request method selection:
@RequestMapping(path = "/orders", method = RequestMethod.GET)
List<Order> ordersWithExplicitMapping() { return service.list(); }
These are alternative mappings; do not register both in the same controller for the same path and method.
11. How do you register a servlet filter?
Implement jakarta.servlet.Filter and register it as a bean. Use a FilterRegistrationBean when the filter needs explicit URL patterns or order. A filter must pass the request onward with chain.doFilter unless it intentionally completes the response.
final class TraceFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
long start = System.nanoTime();
try {
chain.doFilter(request, response);
} finally {
System.out.println("requestNanos=" + (System.nanoTime() - start));
}
}
}
@Bean
FilterRegistrationBean<TraceFilter> traceFilter() {
FilterRegistrationBean<TraceFilter> registration = new FilterRegistrationBean<>();
registration.setFilter(new TraceFilter());
registration.addUrlPatterns("/api/*");
return registration;
}
This sample filter measures processing time for the selected paths. Use structured application logging instead of System.out in a real service.
12. How does Spring Boot provide an embedded server?
A web starter includes an embedded server, so a packaged application can start its HTTP server itself. A Spring MVC starter normally includes Tomcat. Choose a different server by excluding the default server dependency and adding the desired one.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
Check the dependency tree and start the app to confirm which server was selected. The embedded-server guide shows the matching configuration.
13. How can an application run without a web server?
Set the application type to none when the process is a command-line or background application that does not serve HTTP. This is clearer than only removing one server dependency, because another web server might still be available.
spring.main.web-application-type=none
The application context still starts and can run scheduled jobs or command-line runners. No embedded HTTP listener is started by Boot for that application type.
14. How do you inspect Boot’s startup decisions?
Run the application with --debug to log selected framework debug information and the condition evaluation report. This report helps explain why an auto-configuration matched or backed off. It does not turn every application logger to DEBUG.
java -jar application.jar --debug
For a particular package, set logging.level.com.example=DEBUG instead. Use targeted logging and remove noisy settings after diagnosis.
15. How to Check all the Environment Properties in the Application?
Actuator’s env endpoint reports configuration properties subject to exposure, access and sanitization settings. Its usual web path is /actuator/env, unless the management base path is customized. Restrict access and do not expose secrets just to inspect configuration.
Do not forget to enable the endpoint in the properties configuration.
management.endpoints.web.exposure.include=env
16. How does an application read configuration properties?
Boot loads externalized configuration from files, environment variables and command-line arguments. Use Environment for occasional lookups or bind a related group into a typed @ConfigurationProperties class. This keeps names, defaults and validation close to the code that uses them.
@ConfigurationProperties(prefix = "mail")
public record MailSettings(String sender, boolean enabled) {}
For example, mail.sender=team@example.com supplies the sender value. The class must be registered for configuration-properties binding, such as through @ConfigurationPropertiesScan. When a value surprises you, inspect the property source and precedence rather than assuming one file always wins.
17. What does Boot configure for a JPA application?
With the JPA starter, a JDBC driver and data-source settings, Boot can configure the data source, JPA infrastructure and a connection pool when the conditions match. It cannot invent production database credentials or schema policy.
spring.datasource.url=jdbc:postgresql://db.example.com:5432/shop
spring.datasource.username=${DB_USER}
spring.datasource.password=${DB_PASSWORD}
Keep credentials outside the article and application source. Verify the chosen driver, connection pool, entity scan and migration tool in the actual project. A failed connection is not proof that JPA auto-configuration was absent.
18. Why do we use Spring Boot Maven Plugin?
The Spring Boot Maven plugin can run the application and repackage supported archives with their dependencies. Check the plugin documentation for the build tool and Java requirements used by your project.
The plugin provides several goals to work with a Spring Boot application:
spring-boot:repackage: create a jar or war file that is auto-executable. It can replace the regular artifact or can be attached to the build lifecycle with a separate classifier.spring-boot:run: run your Spring Boot application with several options to pass parameters to it.spring-boot:startandstop: integrate your Spring Boot application to theintegration-testphase so that the application starts before it.spring-boot:build-info: generate a build information that can be used by the Actuator.
mvn spring-boot:run -> run the application from the project
mvn package -> package the executable archive when the plugin is configured
The plugin handles Boot-specific packaging and run goals; Maven still handles the ordinary lifecycle.
19. How do executable JAR and WAR packaging differ?
An executable JAR runs the application with its embedded server. A WAR can be deployed to a compatible external servlet container; its server dependency should use the scope expected by that deployment. Choose the format according to the hosting environment.
JAR -> java -jar app.jar -> embedded server
WAR -> external servlet container -> application
With the Spring Boot Maven plugin configured, mvn package can repackage the selected archive. A WAR project also declares <packaging>war</packaging> in pom.xml and configures the application for servlet-container startup. Verify the final artifact by running it in the intended environment; a successful package alone does not prove deployment compatibility.
20. How do you set a logger’s level in Spring Boot?
Boot supplies a logging setup through its starters. Set the level for a specific logger or package in externalized configuration, and keep verbose levels limited to diagnosis.
logging.level.com.example.orders=DEBUG
The property affects that logger namespace. It does not change every dependency’s logging level. The startup --debug flag has a different purpose: selected framework debug output and a condition report.
21. What does Actuator expose?
Actuator adds management endpoints such as health, metrics and configuration inspection. Add the starter, then decide which endpoints should be enabled, exposed over HTTP and protected.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
For example, /actuator/health reports health. The conditions endpoint explains auto-configuration outcomes; env shows environment properties subject to sanitization. They are different endpoints. Do not expose detailed environment or bean information to an untrusted audience. See the Actuator endpoint reference.
22. What is relaxed binding?
Relaxed binding lets Boot map common property-name forms to a typed @ConfigurationProperties field. It is useful when the same setting comes from a properties file or an environment variable.
Java property: logStartupInfo
properties key: spring.main.log-startup-info
environment variable: SPRING_MAIN_LOGSTARTUPINFO
For environment variables, replace dots with underscores, remove dashes and uppercase the result. The rules depend on the property source and target type, so use canonical kebab-case names in documentation. The configuration reference describes the rules.
23. How do unit, slice and full-application tests differ?
A unit test calls a small piece of code without starting Boot. A slice test loads only the framework area under test, such as MVC. @SpringBootTest loads the application context and can start a real server when configured for a random port. Choose the smallest scope that proves the behavior you need.
@WebMvcTest(OrderController.class)
class OrderControllerTest {
// Test MVC request mapping and response behavior.
}
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class OrderApiIntegrationTest {
// Send an HTTP request to the started application.
}
The first test does not prove persistence or the complete security chain. The second can exercise them when the test environment supplies the required collaborators. Boot’s testing reference explains the web environments.
24. What do Spring profiles select?
Profiles activate profile-specific beans and configuration. They are useful for selecting a local adapter or deployment-specific setting, but a profile name does not create an isolated environment or protect secrets by itself.
@Configuration
@Profile("local")
class LocalStorageConfig {
// Local-only bean definitions.
}
java -jar app.jar --spring.profiles.active=local
The command-line argument selects the profile for this run. Keep credentials in an appropriate external secret source regardless of profile.
25. What is Spring Boot DevTools used for?
DevTools adds development-time behavior such as automatic restart when the classpath changes and an optional LiveReload server. It helps a local editing loop; it does not deploy code to production.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
A fully packaged application normally disables these tools. See the DevTools reference for restart and classloader behavior.
26. What is the difference between DevTools restart and LiveReload?
Restart notices a classpath change and starts a fresh application context. LiveReload tells a compatible browser client to refresh after a change. A browser refresh alone does not reload Java classes, and a context restart alone does not guarantee the browser refreshes.
source edit -> build copies class -> DevTools restart -> application is ready
resource edit -> LiveReload signal -> browser reload, if a client is connected
The IDE or build tool must update the classpath before restart can detect a compiled class change.
27. When does a Boot web application need CSRF protection?
A browser can send session cookies automatically. An attacker may exploit that behavior to trigger an unwanted state-changing request from another site. Spring Security’s servlet support enables CSRF protection by default for unsafe requests. The decision to change it depends on how clients authenticate, not whether the endpoint returns JSON.
cookie + unsafe request + valid CSRF token -> process
cookie + unsafe request + no CSRF token -> reject
A bearer-token API may have a different threat model when the browser does not attach credentials automatically. Review the actual clients before changing the default.
28. How does a Spring Boot application configure CORS?
CORS tells browsers which origins may read a cross-origin response. It does not authenticate callers or block non-browser clients. Configure the allowed origins and methods needed by the frontend.
@Configuration
class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("https://app.example.com")
.allowedMethods("GET", "POST");
}
}
If Spring Security is present, make sure its CORS integration handles preflight before authentication rejects a request with no session cookie. Test both the preflight and actual browser request.
29. How can Boot serve HTTPS?
Provide a certificate and private key through a Java KeyStore, PEM files or a named SSL bundle, then connect that material to the embedded server. The certificate must match the hostname clients use.
server.port=8443
server.ssl.bundle=webserver
The example assumes that an SSL bundle named webserver is already configured. Do not combine server.ssl.bundle with separate server.ssl.key-store or PEM options. The SSL reference explains bundle definitions and the web-server guide explains server integration.