spring-bootinterviewjavafreshers
Top 30 Spring Boot Interview Questions for Freshers 2026 — With Answers
Siva Prasad Galaba· Staff Engineer at Crunchyroll | Founder, CodeBegun·
The most asked Spring Boot interview questions for freshers in 2026, with clear answers. Covers core concepts, annotations, JPA, security, and real interview scenarios.
These are the Spring Boot questions that come up most frequently in fresher interviews in Hyderabad — drawn from what our placed students report back. I've organized them by concept, with answers that are detailed enough to be useful but concise enough to actually say in an interview.
---
## Section 1 — Spring Boot Basics
### 1. What is Spring Boot and how is it different from Spring Framework?
**Spring Framework** is a comprehensive Java application framework that requires a lot of manual configuration — XML or Java-based beans, servlet configuration, dependency management.
**Spring Boot** is an opinionated layer on top of Spring that eliminates most of that configuration:
- Auto-configuration — Spring Boot detects what's on your classpath and configures beans automatically
- Embedded server — Tomcat is included; you don't configure a separate server
- Starter dependencies — `spring-boot-starter-web` pulls in everything needed for a REST API
- `spring-boot-starter-*` convention makes dependency management consistent
In short: Spring Boot makes Spring production-ready with minimal setup.
### 2. What does `@SpringBootApplication` do?
It's a composite annotation combining three annotations:
- `@Configuration` — marks the class as a source of bean definitions
- `@EnableAutoConfiguration` — enables Spring Boot's auto-configuration mechanism
- `@ComponentScan` — scans the current package and sub-packages for Spring components
### 3. What is auto-configuration in Spring Boot?
Auto-configuration inspects the classpath and beans available and automatically configures Spring components. For example, if `spring-boot-starter-data-jpa` is on the classpath and you have a `DataSource` configured, Spring Boot automatically sets up `EntityManagerFactory`, transaction management, and JPA repositories.
You can see what was auto-configured by enabling the `--debug` flag or checking `ConditionEvaluationReport`.
### 4. What is the Spring Boot starter dependency?
A starter is a convenient dependency descriptor that pulls in a set of related transitive dependencies. Instead of manually adding 7 JARs for web development, you add one:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
```
Common starters: `starter-web`, `starter-data-jpa`, `starter-security`, `starter-test`, `starter-actuator`.
### 5. What is `application.properties` used for?
It's the central configuration file for a Spring Boot application. You configure database connections, server port, logging levels, JPA settings, and any custom properties here:
```properties
server.port=8081
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.jpa.show-sql=true
logging.level.org.springframework=DEBUG
```
`application.yml` is the YAML equivalent and preferred for hierarchical configuration.
---
## Section 2 — REST API Annotations
### 6. What is the difference between `@Controller` and `@RestController`?
`@Controller` returns view names (used with Thymeleaf/JSP templating). You need `@ResponseBody` on each method to return data directly.
`@RestController` = `@Controller` + `@ResponseBody` on every method. Every method returns data serialized to JSON automatically. Use `@RestController` for REST APIs.
### 7. What does `@RequestMapping` do?
Maps HTTP requests to handler methods. At the class level, it sets a base URL path. At the method level, it specifies the exact endpoint:
```java
@RestController
@RequestMapping("/api/students")
public class StudentController {
@GetMapping("/{id}") // maps to GET /api/students/{id}
@PostMapping // maps to POST /api/students
@PutMapping("/{id}") // maps to PUT /api/students/{id}
@DeleteMapping("/{id}") // maps to DELETE /api/students/{id}
}
```
### 8. What is `@PathVariable` vs `@RequestParam`?
`@PathVariable` extracts values from the URI path:
```java
@GetMapping("/students/{id}")
public Student getById(@PathVariable Long id) { ... }
// GET /students/5 → id = 5
```
`@RequestParam` extracts query string parameters:
```java
@GetMapping("/students")
public List<Student> search(@RequestParam String city) { ... }
// GET /students?city=Hyderabad → city = "Hyderabad"
```
### 9. What is `@RequestBody` and when do you use it?
`@RequestBody` binds the HTTP request body (JSON) to a Java object. Jackson deserializes the JSON automatically. Used with POST and PUT requests:
```java
@PostMapping
public ResponseEntity<Student> create(@RequestBody Student student) {
return ResponseEntity.status(201).body(service.save(student));
}
```
### 10. How do you validate request body in Spring Boot?
Add `@Valid` to the method parameter and annotate the entity/DTO with Bean Validation annotations:
```java
public class Student {
@NotBlank(message = "Name is required")
private String name;
@Email(message = "Invalid email")
private String email;
@Min(value = 18, message = "Must be at least 18")
private int age;
}
@PostMapping
public ResponseEntity<?> create(@Valid @RequestBody Student student) { ... }
```
Validation errors throw `MethodArgumentNotValidException`, handled by `@ControllerAdvice`.
---
## Section 3 — Dependency Injection
### 11. What is Dependency Injection and how does Spring implement it?
Dependency Injection means objects receive their dependencies from outside rather than creating them. Spring implements it through its IoC (Inversion of Control) container.
```java
@Service
public class OrderService {
private final OrderRepository repo;
// Constructor injection — preferred
public OrderService(OrderRepository repo) {
this.repo = repo;
}
}
```
Spring sees `@Service`, creates an instance, detects the `OrderRepository` dependency, and injects it automatically.
### 12. What is the difference between `@Component`, `@Service`, `@Repository`, and `@Controller`?
All four are specializations of `@Component` and make a class a Spring bean. The difference is semantic — they signal the layer:
| Annotation | Layer | Extra behavior |
|---|---|---|
| `@Component` | Generic | None |
| `@Controller` | Presentation | Marks as request handler |
| `@Service` | Business logic | None (semantic only) |
| `@Repository` | Data access | Translates database exceptions |
### 13. What is `@Autowired` and should you use it on fields?
`@Autowired` tells Spring to inject a dependency. Field injection works but is not recommended:
```java
// Not recommended
@Autowired
private UserRepository repo;
// Recommended — constructor injection
private final UserRepository repo;
public UserService(UserRepository repo) { this.repo = repo; }
```
Constructor injection makes dependencies explicit, enables immutability, and works with testing frameworks without Spring.
---
## Section 4 — Spring Data JPA
### 14. What is Spring Data JPA?
A Spring abstraction over JPA that eliminates boilerplate data access code. Extending `JpaRepository<Entity, ID>` gives you `save()`, `findById()`, `findAll()`, `deleteById()` and many more without any implementation.
### 15. What is the difference between `save()` and `saveAndFlush()`?
`save()` saves to the persistence context (first-level cache). The actual SQL may execute later, at the end of the transaction.
`saveAndFlush()` immediately synchronizes the persistence context with the database. Use it when you need to ensure the write happens before the next operation in the same transaction.
### 16. How do you write custom queries in Spring Data JPA?
Three ways:
```java
// 1. Method name derivation
List<Student> findByCity(String city);
List<Student> findByCityAndCourse(String city, String course);
// 2. JPQL with @Query
@Query("SELECT s FROM Student s WHERE s.city = :city AND s.score > :min")
List<Student> findTopStudentsInCity(@Param("city") String city, @Param("min") int min);
// 3. Native SQL
@Query(value = "SELECT * FROM students WHERE city = ?1", nativeQuery = true)
List<Student> findByCityNative(String city);
```
### 17. What is `@Transactional`?
Marks a method to run within a database transaction. Spring begins a transaction before the method, commits on success, and rolls back on unchecked exceptions.
```java
@Transactional
public void transferFunds(Long fromId, Long toId, BigDecimal amount) {
debit(fromId, amount); // if this fails
credit(toId, amount); // this won't happen — transaction rolls back
}
```
---
## Section 5 — Exception Handling
### 18. How do you handle exceptions globally in Spring Boot?
Use `@ControllerAdvice` with `@ExceptionHandler` methods:
```java
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<ErrorResponse> handleNotFound(ResourceNotFoundException ex) {
return ResponseEntity.status(404)
.body(new ErrorResponse(ex.getMessage(), 404));
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ErrorResponse> handleValidation(MethodArgumentNotValidException ex) {
String message = ex.getBindingResult().getFieldErrors()
.stream().map(fe -> fe.getField() + ": " + fe.getDefaultMessage())
.collect(Collectors.joining(", "));
return ResponseEntity.badRequest().body(new ErrorResponse(message, 400));
}
}
```
### 19. What HTTP status codes should you use for REST APIs?
| Scenario | Status Code |
|---|---|
| GET success | 200 OK |
| POST success (created) | 201 Created |
| DELETE success | 204 No Content |
| Bad request / validation | 400 Bad Request |
| Unauthorized | 401 Unauthorized |
| Forbidden | 403 Forbidden |
| Not found | 404 Not Found |
| Server error | 500 Internal Server Error |
---
## Section 6 — Spring Boot Actuator & Other
### 20. What is Spring Boot Actuator?
A library that adds production-ready monitoring endpoints to your application:
- `/actuator/health` — application health status
- `/actuator/info` — app info (version, build details)
- `/actuator/metrics` — JVM metrics, request counts, errors
- `/actuator/env` — environment properties
Add `spring-boot-starter-actuator` to your dependencies to enable it.
### 21. What is the difference between `@Bean` and `@Component`?
`@Component` auto-detects a class through classpath scanning.
`@Bean` is used inside `@Configuration` classes to manually define beans — useful for third-party classes you can't annotate:
```java
@Configuration
public class AppConfig {
@Bean
public ModelMapper modelMapper() {
return new ModelMapper(); // third-party class, can't add @Component to it
}
}
```
### 22. How do you run code on Spring Boot application startup?
Implement `CommandLineRunner` or `ApplicationRunner`:
```java
@Component
public class DataSeeder implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
// runs after context is fully loaded
seedInitialData();
}
}
```
---
## Common Mistakes in Spring Boot Interviews
1. **Using field injection** when asked about best practices — always say constructor injection
2. **Confusing `@Controller` and `@RestController`** — know that `@RestController` adds `@ResponseBody`
3. **Not knowing what `@Transactional` does** — this comes up in 80% of interviews
4. **Saying "I use JPA" without knowing what JPQL is**
5. **Not being able to explain the layered architecture** — Controller → Service → Repository
---
Want to practice these in a real coding environment? CodeBegun's program includes weekly Spring Boot labs and 10 mock interview sessions. [View the program →](/java-full-stack) or [chat with us on WhatsApp](https://wa.me/916301099587).
Siva Prasad Galaba
Staff Engineer at Crunchyroll | Founder, CodeBegun
Founder of CodeBegun. 15+ years building Java systems at companies like Crunchyroll. Teaching the next generation to code the way the industry actually works.
