Top 50 Spring Boot Interview Questions & Answers for Freshers (2025)
If you are a fresher or a Java developer with less than 2 years of experience, Spring Boot interviews can feel overwhelming. Instead of random question lists, this guide explains how things really work in Spring Boot with simple examples, so you can answer confidently in any interview.
- Core Spring Boot concepts (Starters, Auto-Configuration, Embedded server)
- How to build REST APIs with controllers, JSON, validation and global exception handling
- Spring Data JPA basics – entities, repositories and transactions
- Actuator, profiles, properties and common production-ready features
- 50 real interview-style questions with short and deep answers + follow-ups
Section 1 – Spring Boot Fundamentals (Q1–Q10)
1. What is Spring Boot?
Short answer: Spring Boot is a framework built on top of Spring that lets you create production-ready applications quickly using auto-configuration, starter dependencies and embedded servers, with minimal configuration.
Deeper explanation:
- Traditional Spring apps needed a lot of XML/Java config and a separate application server (Tomcat, JBoss).
- Spring Boot gives sensible defaults and configures many things automatically using
@EnableAutoConfiguration. - You usually run the app as a standalone
java -jar– no external server installation required.
Follow-up question: “Is Spring Boot a replacement for Spring?”
Answer: No, it is an opinionated way of using the Spring Framework.
2. What problem does Spring Boot solve?
It solves three main problems:
- Too much configuration – XML, dispatcher servlet, view resolvers, etc.
- Dependency hell – managing correct versions of many Spring libraries.
- Slow startup for simple services – deploying WAR files to external servers.
Spring Boot makes projects easier to bootstrap, easier to run and easier to move to production.
3. What is @SpringBootApplication?
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
@SpringBootApplication is a convenience annotation that combines:
@Configuration– marks the class as a source of bean definitions.@EnableAutoConfiguration– tells Spring Boot to configure beans based on classpath and properties.@ComponentScan– scans the current package and sub-packages for Spring components.
4. What is a Spring Boot Starter?
A starter is a Maven/Gradle dependency that groups commonly used libraries with compatible versions.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
spring-boot-starter-webbrings Spring MVC, JSON support, validation, embedded Tomcat etc.- You don’t search for each small dependency manually.
Follow-up: Name 3 other starters → spring-boot-starter-data-jpa, spring-boot-starter-security, spring-boot-starter-test.
5. What is Auto-Configuration in Spring Boot?
Auto-configuration tries to create and configure beans for you based on:
- What classes are present on the classpath
- What beans you have already defined
- What properties you provide in
application.properties/application.yml
Internally, Spring Boot loads many *AutoConfiguration classes. Each configuration uses conditional annotations like:
@ConditionalOnClass– apply if a specific class is present@ConditionalOnProperty– apply if a specific property has a value
6. How do you disable a specific auto-configuration?
@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })
public class DemoApplication {
...
}
Or with properties:
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
7. What is an embedded server in Spring Boot?
Instead of deploying a WAR to an external Tomcat, Spring Boot packages a server (Tomcat/Jetty/Undertow) inside the application JAR.
- Default server: Tomcat (through
spring-boot-starter-web) - Application is started using
SpringApplication.run()which starts the embedded server and registers Spring MVC.
Follow-up: How to switch to Jetty?
Remove Tomcat starter and add spring-boot-starter-jetty.
8. What is the default port in Spring Boot and how to change it?
- Default port: 8080
# application.properties
server.port=9090
You can also change it programmatically using SpringApplicationBuilder or by configuring an WebServerFactoryCustomizer, but properties are enough for fresher level.
9. What is the difference between Spring and Spring Boot?
| Spring Framework | Spring Boot |
|---|---|
| Provides core features (IoC, AOP, MVC, etc.) | Opinionated way to build apps using Spring |
| Requires manual configuration | Provides auto-configuration and starters |
| Typically deployed on external server | Runs as standalone JAR with embedded server |
10. What is the entry point of a Spring Boot application?
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
This bootstraps the Spring context and starts the embedded server.
Section 2 – Configuration & Profiles (Q11–Q17)
11. What are application.properties and application.yml?
These files hold configuration values for your application such as database URLs, ports, logging levels etc.
application.properties– key=value format.application.yml– YAML format (hierarchical, cleaner for complex configs).
Both are loaded automatically from the classpath (src/main/resources).
12. What is a Spring Profile and why is it useful?
Profiles allow you to have different configurations for different environments such as dev, test, prod.
# application-dev.properties
server.port=8081
# application-prod.properties
server.port=80
spring.profiles.active=dev
In code you can target profiles using:
@Profile("dev")
@Component
public class DevMailSender implements MailSender { ... }
13. What is @ConfigurationProperties and how is it different from @Value?
@Value injects a single property:
@Value("${app.name}")
private String appName;
@ConfigurationProperties binds a group of properties to a POJO:
@ConfigurationProperties(prefix = "app.mail")
public class MailProperties {
private String host;
private int port;
// getters/setters
}
It is better for structured config, type-safety and IDE support.
14. In what order does Spring Boot load configuration values?
Priority from highest to lowest (simplified for freshers):
- Command line arguments
- Environment variables
application-{profile}.propertiesapplication.properties- Default values in code
If a property appears in multiple places, the one with higher priority wins.
15. How can you access Spring environment properties in code?
@RestController
public class InfoController {
private final Environment env;
public InfoController(Environment env) {
this.env = env;
}
@GetMapping("/env")
public String env() {
return env.getProperty("spring.application.name", "demo");
}
}
16. What is the use of spring-boot-devtools?
DevTools improves developer productivity by providing:
- Automatic restart on classpath changes
- LiveReload support for browser refresh
- Development-friendly defaults (e.g. disable caching)
It should never be used in production.
17. How do you externalize configuration in Spring Boot?
You can place application.properties outside the JAR and point to it using:
java -jar app.jar --spring.config.location=/opt/config/
This is very common in Docker/Kubernetes setups where configuration changes without rebuilding the JAR.
Section 3 – Building REST APIs (Q18–Q27)
18. Difference between @Controller and @RestController?
| @Controller | @RestController |
|---|---|
| Used for MVC web pages (JSP/Thymeleaf) | Used for REST APIs |
| Methods return view names | Methods return response body (JSON/XML) |
Needs @ResponseBody | Implicit @ResponseBody |
19. How do you create a simple REST endpoint?
@RestController
@RequestMapping("/api/hello")
public class HelloController {
@GetMapping
public String hello() {
return "Hello Spring Boot!";
}
}
Here:
@RestController=@Controller+@ResponseBody@RequestMappingdefines base path.@GetMappinghandles GET requests.
20. What is @PathVariable vs @RequestParam?
@PathVariable→ part of the URL path
@GetMapping("/users/{id}")
public User getUser(@PathVariable Long id) { ... }
@RequestParam→ query parameter
@GetMapping("/users")
public List<User> findByStatus(@RequestParam String status) { ... }
21. How do you accept JSON in a POST request?
@PostMapping("/users")
public User createUser(@RequestBody UserRequest request) {
...
}
@RequestBody tells Spring to convert the JSON body to a Java object using Jackson.
22. How do you return a different HTTP status code?
Use ResponseEntity:
@PostMapping("/users")
public ResponseEntity<User> create(@RequestBody UserRequest request) {
User saved = service.createUser(request);
return ResponseEntity
.status(HttpStatus.CREATED)
.body(saved);
}
23. How can you validate request data?
public class UserRequest {
@NotBlank
private String name;
@Email
private String email;
}
@PostMapping("/users")
public ResponseEntity<User> create(@Valid @RequestBody UserRequest request) {
...
}
Add spring-boot-starter-validation to enable Jakarta Bean Validation.
24. How do you handle exceptions globally in Spring Boot?
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(UserNotFoundException.class)
public ResponseEntity<String> handle(UserNotFoundException ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(ex.getMessage());
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Map<String,String>> handleValidation(
MethodArgumentNotValidException ex) {
Map<String,String> errors = new HashMap<>();
ex.getBindingResult().getFieldErrors()
.forEach(fe -> errors.put(fe.getField(), fe.getDefaultMessage()));
return ResponseEntity.badRequest().body(errors);
}
}
@RestControllerAdvice applies to all controllers and converts exceptions into meaningful HTTP responses.
25. What is DispatcherServlet?
It is the front controller in Spring MVC. All HTTP requests go through it. It:
- Finds appropriate controller method
- Handles argument resolution
- Converts return value to HTTP response (JSON, view, etc.)
Spring Boot automatically registers DispatcherServlet for you.
26. How do you enable CORS in Spring Boot?
@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "http://localhost:3000")
public class ApiController {
...
}
Or globally using a WebMvcConfigurer bean.
27. How do you log requests in Spring Boot?
Simple way is to use a Filter or HandlerInterceptor, or enable built-in logging:
logging.level.org.springframework.web.filter.CommonsRequestLoggingFilter=DEBUG
For more control you can create your own OncePerRequestFilter.
Section 4 – Spring Data JPA (Q28–Q36)
28. What is Spring Data JPA?
Spring Data JPA is part of Spring Data that simplifies working with relational databases using JPA.
- Provides repository interfaces like
JpaRepositorywith CRUD operations. - Removes boilerplate for implementing DAO layers.
29. How do you define an Entity class?
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String name;
private String email;
// getters and setters
}
30. What is JpaRepository?
public interface UserRepository extends JpaRepository<User, Long> {
List<User> findByName(String name);
boolean existsByEmail(String email);
}
JpaRepository extends PagingAndSortingRepository and CrudRepository, adding extra methods.
31. How does Spring Data derive query methods from method names?
Method names follow a pattern: findBy<Field>, findBy<Field>And<Field2>, findTop10ByOrderByCreatedAtDesc etc.
Example:
List<User> findByStatusAndCity(String status, String city);
Spring generates the JPQL at runtime.
32. How do you write custom JPQL or native queries?
@Query("select u from User u where u.email like %:keyword%")
List<User> search(@Param("keyword") String keyword);
For native:
@Query(value = "select * from users u where u.status = ?1",
nativeQuery = true)
List<User> findByStatus(String status);
33. How do you configure database connection in Spring Boot?
spring.datasource.url=jdbc:mysql://localhost:3306/app_db
spring.datasource.username=root
spring.datasource.password=secret
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
This is enough for simple apps; Boot auto-configures DataSource, EntityManagerFactory and transaction manager.
34. What are common values for spring.jpa.hibernate.ddl-auto?
- none – no schema changes (recommended for prod)
- validate – validate schema, fail if mismatched
- update – update schema based on entity changes
- create – drop and create schema at startup
- create-drop – create on startup and drop on shutdown
35. What is Lazy vs Eager fetching?
- EAGER – related entities are loaded immediately.
- LAZY – related entities are loaded only when accessed.
@OneToMany(mappedBy = "user", fetch = FetchType.LAZY)
private List<Order> orders;
36. How is transaction management handled in Spring Boot?
Spring Boot auto-configures a transaction manager if JPA is on the classpath.
You mark methods or classes with @Transactional:
@Service
public class UserService {
@Transactional
public void updateEmail(Long userId, String email) {
User user = repo.findById(userId)
.orElseThrow(UserNotFoundException::new);
user.setEmail(email);
}
}
Spring creates a proxy that opens/closes transactions around the method and rolls back on runtime exceptions by default.
Section 5 – Actuator, Logging & Security Basics (Q37–Q44)
37. What is Spring Boot Actuator?
Actuator adds production-ready features such as health checks and metrics.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
Common endpoints:
/actuator/health/actuator/info/actuator/metrics
management.endpoints.web.exposure.include=health,info,metrics
38. How to customize /actuator/info output?
info.app.name=Spring Boot Interview App
info.app.version=1.0.0
info.app.description=Simple app for learning
Or programmatically with an InfoContributor bean.
39. How is logging configured by default in Spring Boot?
Spring Boot uses Logback under the hood and logs to the console.
logging.level.root=INFO
logging.level.com.example=DEBUG
logging.file.name=app.log
40. What is Spring Security in context of Spring Boot?
Spring Security is a separate framework for authentication and authorization. When you add spring-boot-starter-security, Spring Boot:
- Secures all endpoints by default
- Generates a default user and random password (logged on startup)
From Spring Boot 3 / Spring Security 6, configuration is done with lambdas and the new SecurityFilterChain bean instead of WebSecurityConfigurerAdapter.
41. How do you permit all requests to a specific endpoint?
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> auth
.requestMatchers("/public/**").permitAll()
.anyRequest().authenticated()
)
.httpBasic(Customizer.withDefaults());
return http.build();
}
Section 6 – Testing in Spring Boot (Q42–Q46)
42. What is spring-boot-starter-test?
It is a test starter that bundles:
- JUnit
- Spring Test
- Mockito
- JSONassert, Hamcrest, AssertJ, etc.
It gives everything you need for unit and integration tests in Spring Boot.
43. What does @SpringBootTest do?
@SpringBootTest
class UserServiceIT {
@Autowired
private UserService userService;
@Test
void shouldCreateUser() {
...
}
}
@SpringBootTest starts the full application context (like running the app) and is used for integration tests.
It is heavier than slice tests but ensures all beans are wired correctly.
44. What is @WebMvcTest used for?
@WebMvcTest(UserController.class)
class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private UserService userService;
}
It loads only the MVC layer – controllers, filters, etc. It does not load the whole application or real database. Good for testing controller behavior in isolation.
45. How do you test JPA repositories in Spring Boot?
@DataJpaTest
class UserRepositoryTest {
@Autowired
private UserRepository userRepository;
@Test
void saveAndFindUser() {
User user = new User();
user.setName("John");
userRepository.save(user);
List<User> users = userRepository.findByName("John");
...
}
}
@DataJpaTest configures an in-memory database by default and scans only JPA components.
Section 7 – Misc & Practical Questions (Q46–Q50)
46. How do you run a Spring Boot application from the command line?
- Build JAR:
mvn clean package - Run:
java -jar target/app-0.0.1-SNAPSHOT.jar
47. How can you pass arguments on startup?
java -jar app.jar --server.port=9090 --spring.profiles.active=prod
These override configuration properties.
48. How do you create a command-line runner in Spring Boot?
@Component
public class DataLoader implements CommandLineRunner {
private final UserRepository userRepository;
public DataLoader(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Override
public void run(String... args) {
// runs once on startup
if (userRepository.count() == 0) {
userRepository.save(new User("admin@example.com"));
}
}
}
Useful for inserting sample data or running startup logic.
49. What is the difference between JAR and WAR packaging in Spring Boot?
- JAR – default for Spring Boot, runs with embedded server; ideal for microservices.
- WAR – used when deploying to external app server (Tomcat, WildFly).
For fresher roles, it’s usually enough to say “we use JAR with embedded Tomcat for microservices”.
50. If your Spring Boot application is not starting, how would you debug it?
Typical steps to mention in an interview:
- Check logs for the root cause exception (database connection, port in use, bean creation failure).
- Run with
--debugflag to show auto-configuration decisions. - Check circular dependencies or missing bean definitions.
- Temporarily comment/remove configuration to isolate the problem.
Quick Revision Sheet
- @SpringBootApplication =
@Configuration+@EnableAutoConfiguration+@ComponentScan - Default port = 8080, change with
server.port - Use Starters to pull correct dependencies
- Use Profiles for different env configs
- @RestController for JSON APIs, @Controller for views
- Spring Data JPA +
JpaRepositoryfor DB CRUD - Actuator for health & metrics
- DevTools for faster development reload
๐ What to Learn After Spring Boot Interview Basics?
Clearing a fresher-level Spring Boot interview requires strong fundamentals. To grow beyond basics and become job-ready, explore these essential Spring Boot topics.
๐ท️ Spring Boot Annotations for REST APIs
Learn the most important annotations used in real Spring Boot REST applications.
๐ฏ Controller vs RestController
Understand the difference between MVC and REST controllers — a common interview question.
๐งพ REST API Validation Annotations
Learn how Spring Boot validates request data using built-in annotations.
✅ Custom Validation Annotations
Go beyond basics by creating reusable custom validation logic.
๐จ Global Exception Handling
Handle errors consistently using
@ControllerAdvice.
๐ Spring Boot JPA Basics
Learn how Spring Boot works with databases using JPA and Hibernate.
๐งฉ Spring Boot CRUD API Example
Build your first complete REST API using Spring Boot and a database.
๐ผ Spring Boot Interview Questions (2–5 Years)
Upgrade your interview preparation with real-world Spring Boot scenarios.