Interview Questions SpringBoot

By: zigmoid
Posted on: 05/04/2025

1. What is Spring Boot?

Answer:
Spring Boot is a Java-based framework that makes it easy to create stand-alone, production-grade Spring applications. It simplifies configuration by auto-configuring beans, using embedded servers like Tomcat, and reducing boilerplate code.


2. What are the advantages of Spring Boot?

Answer:

  • No XML configuration required
  • Embedded servers (Tomcat, Jetty) β€” no WAR deployment needed
  • Auto-configuration of Spring beans
  • Production-ready with built-in monitoring and metrics
  • Quick to set up and run (good for microservices)

3. What is the difference between Spring and Spring Boot?

Spring (Core)Spring Boot
Requires XML configNo XML β€” uses annotations & auto config
Need to deploy WARUses embedded servers
Manual setupConvention over configuration

4. What is @SpringBootApplication?

Answer:
@SpringBootApplication is a combination of:

  • @Configuration: marks class as a bean definition source
  • @EnableAutoConfiguration: enables auto-config
  • @ComponentScan: scans for components in the package

5. How do you create a Spring Boot project?

Answer:

  • Use https://start.spring.io
  • Choose dependencies like Spring Web, Spring Data JPA, H2, etc.
  • Download ZIP, unzip, open in IDE, and run main class.

6. What is application.properties / application.yml?

Answer:
It’s a configuration file where you define app settings like port, DB URL, logging level, etc.

propertiesCopyEditserver.port=8081
spring.datasource.url=jdbc:mysql://localhost:3306/mydb

7. What is a Spring Boot starter?

Answer:
A starter is a pre-packaged set of dependencies for common tasks. Example:

  • spring-boot-starter-web β†’ for REST APIs (Spring MVC + Tomcat + JSON)
  • spring-boot-starter-data-jpa β†’ for JPA/Hibernate integration

8. How do you run a Spring Boot app?

Answer:

  • Run main() method in the class annotated with @SpringBootApplication
  • Or use mvn spring-boot:run or gradle bootRun

9. What is an embedded server?

Answer:
It means the app runs its own web server (like Tomcat) internally β€” you don’t need to deploy WARs to an external server.


10. What is dependency injection in Spring?

Answer:
It’s when Spring automatically provides the objects (beans) your class needs β€” instead of you creating them manually using new.


11. What is @RestController?

Answer:
It’s used to create REST APIs. It’s a combo of:

  • @Controller
  • @ResponseBody (returns data directly, not a view)
javaCopyEdit@RestController
public class HelloController {
    @GetMapping("/hello")
    public String sayHello() {
        return "Hi there!";
    }
}

12. What is the default port of Spring Boot?

Answer:
Port 8080. You can change it using:

propertiesCopyEditserver.port=9090

13. How do you handle exceptions in Spring Boot?

Answer:
Using @ControllerAdvice and @ExceptionHandler.

javaCopyEdit@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handle(Exception e) {
        return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

14. What is a Bean in Spring?

Answer:
A bean is just an object that’s managed by the Spring container β€” it’s created, injected, and wired by Spring automatically.


15. What is @Autowired?

Answer:
Used to automatically inject a bean into another bean (dependency injection).

javaCopyEdit@Autowired
private MyService myService;

16. What is @Component, @Service, @Repository, and @Controller?

Answer:

They all make classes into Spring-managed beans. The difference is semantic (used for readability and Spring’s internal behaviors):

  • @Component – Generic stereotype for any Spring-managed class.
  • @Service – Business logic layer.
  • @Repository – Data access layer (adds exception translation for JPA).
  • @Controller – Used in MVC to handle web requests.

17. What is @GetMapping, @PostMapping, etc.?

Answer:

They are shortcuts for defining REST endpoints:

javaCopyEdit@GetMapping("/user")   // Handles GET requests
@PostMapping("/user")  // Handles POST requests
@PutMapping("/user")   // Handles PUT requests
@DeleteMapping("/user") // Handles DELETE requests

18. How does Spring Boot handle database operations?

Answer:

With Spring Data JPA. You create an interface that extends JpaRepository, and BOOM β€” CRUD operations work out of the box.

javaCopyEditpublic interface UserRepository extends JpaRepository<User, Long> { }

19. What is application.properties vs application.yml?

Answer:

Same purpose, different syntax:

  • .properties uses key-value pairs
  • .yml uses indentation-based YAML format

YAML is cleaner, especially for complex settings like DB config or nested properties.


20. What is Spring Initializr?

Answer:

A web tool (start.spring.io) that helps generate a Spring Boot starter project with all dependencies, build tools (Maven/Gradle), Java version, etc.


21. How do you connect Spring Boot with a database?

Answer:

By adding DB config in application.properties:

propertiesCopyEditspring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=pass
spring.jpa.hibernate.ddl-auto=update

22. What is Spring Boot DevTools?

Answer:

A developer-friendly tool that enables:

  • Auto-restart on code change
  • LiveReload in browser
  • Better logging

Add it via Maven:

xmlCopyEdit<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-devtools</artifactId>
</dependency>

23. What is @RequestParam vs @PathVariable?

Answer:

  • @RequestParam: gets query parameters
    /user?id=1
  • @PathVariable: gets value from URI
    /user/1
javaCopyEdit@GetMapping("/user")
public String getById(@RequestParam int id) { }

@GetMapping("/user/{id}")
public String getById(@PathVariable int id) { }

24. What is actuator in Spring Boot?

Answer:

Spring Boot Actuator provides endpoints to monitor and manage your app (health, metrics, info, etc.).

Add it with:

xmlCopyEdit<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

25. How do you log in Spring Boot?

Answer:

Using SLF4J with Logback (default logger). Use:

javaCopyEditprivate static final Logger logger = LoggerFactory.getLogger(MyClass.class);

Control log level via application.properties:

propertiesCopyEditlogging.level.org.springframework=INFO
logging.level.com.myapp=DEBUG

26. What is autoconfiguration in Spring Boot?

Answer:

Spring Boot automatically configures beans based on the dependencies on your classpath. Like, if you add spring-boot-starter-web, it sets up a dispatcher servlet, Jackson, etc., for you.


27. What is a Microservice? Is Spring Boot good for it?

Answer:

A microservice is a small, independently deployable service that does one thing well. Spring Boot is perfect for microservices because it’s lightweight, fast to start, and has embedded servers.


28. What is H2 database and why use it?

Answer:

H2 is an in-memory database (gone when app stops) β€” super useful for dev/testing. Add with:

xmlCopyEdit<dependency>
  <groupId>com.h2database</groupId>
  <artifactId>h2</artifactId>
</dependency>

29. How do you create a REST API in Spring Boot?

Answer:
Just annotate your class with @RestController, and use mappings:

javaCopyEdit@RestController
public class UserController {

    @GetMapping("/users")
    public List<User> getAllUsers() {
        return userRepository.findAll();
    }
}

30. What is the Spring Boot starter dependency for building web apps?

Answer:
spring-boot-starter-web β†’ includes Spring MVC + Jackson (JSON) + embedded Tomcat.


31. What is @Entity in Spring Boot?

Answer:

@Entity marks a class as a JPA entity β€” it maps to a database table.

javaCopyEdit@Entity
public class User {
   @Id
   private Long id;
   private String name;
}

32. What is the role of @Id and @GeneratedValue?

Answer:

  • @Id: Marks the primary key of the entity
  • @GeneratedValue: Auto-generates the ID (like auto-increment)
javaCopyEdit@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

33. What is Spring Data JPA?

Answer:

It’s a Spring project that simplifies database interactions using interfaces. You don’t write SQL β€” just extend JpaRepository.


34. What is the difference between CrudRepository and JpaRepository?

CrudRepositoryJpaRepository
Basic CRUD operationsIncludes pagination + batch ops
LightweightMore features (e.g. flush)

35. What is the use of @RequestBody?

Answer:

It maps the incoming JSON from a POST or PUT request to a Java object.

javaCopyEdit@PostMapping("/users")
public String createUser(@RequestBody User user) { }

36. What is CORS and how do you enable it in Spring Boot?

Answer:

CORS = Cross-Origin Resource Sharing
To enable:

javaCopyEdit@CrossOrigin(origins = "*")
@GetMapping("/data")
public String getData() { }

Or globally via config.


37. How do you return JSON in a Spring Boot API?

Answer:

Spring Boot auto-converts your Java object to JSON using Jackson:

javaCopyEdit@GetMapping("/user")
public User getUser() {
    return new User("Alice", 22);
}

38. What is the default JSON library used in Spring Boot?

Answer:

Jackson (faster than GSON, widely supported)


39. How do you validate input in Spring Boot?

Answer:

Use Bean Validation (javax.validation) + @Valid:

javaCopyEditpublic class User {
    @NotBlank
    private String name;
}

@PostMapping("/users")
public ResponseEntity<?> save(@Valid @RequestBody User user) { }

40. How to handle 404 / 500 errors globally?

Answer:

Use @ControllerAdvice or customize ErrorController.

javaCopyEdit@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleError(Exception e) {
        return new ResponseEntity<>("Something broke!", HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

41. How do you use pagination in Spring Boot?

Answer:

Use Pageable with JpaRepository:

javaCopyEdit@GetMapping("/users")
public Page<User> getUsers(Pageable pageable) {
    return userRepository.findAll(pageable);
}

42. What is the purpose of @EnableAutoConfiguration?

Answer:

It tells Spring Boot to guess and configure beans based on dependencies in the classpath. You rarely use it manually because it’s included in @SpringBootApplication.


43. What is the use of profiles in Spring Boot?

Answer:

Spring profiles help manage different configs for dev, test, and prod environments.

propertiesCopyEdit# application-dev.properties
server.port=8081

Set profile via:

bashCopyEdit-Dspring.profiles.active=dev

44. What is the use of @Configuration and @Bean?

Answer:

  • @Configuration: Marks class for bean definitions.
  • @Bean: Defines a bean to be managed by Spring.
javaCopyEdit@Configuration
public class AppConfig {
    @Bean
    public MyService service() {
        return new MyService();
    }
}

45. How to schedule tasks in Spring Boot?

Answer:

Use @Scheduled with @EnableScheduling:

javaCopyEdit@Scheduled(fixedRate = 5000)
public void printHello() {
    System.out.println("Hello every 5 sec!");
}

46. How do you secure a Spring Boot app?

Answer:

Add Spring Security starter, configure auth using:

javaCopyEdit@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().authenticated().and().formLogin();
    }
}

47. What are the common annotations used in Spring Boot?

Answer:

  • @RestController
  • @Autowired
  • @RequestMapping
  • @Service
  • @Repository
  • @Entity
  • @SpringBootApplication

48. How does Spring Boot reduce boilerplate code?

Answer:

  • Auto-configuration
  • Embedded server
  • Starter dependencies
  • Convention-over-configuration

49. What is the structure of a typical Spring Boot project?

cssCopyEditsrc/
 └── main/
     β”œβ”€β”€ java/
     β”‚    └── com.example.app/
     β”‚         β”œβ”€β”€ controller/
     β”‚         β”œβ”€β”€ service/
     β”‚         β”œβ”€β”€ repository/
     β”‚         └── Application.java
     └── resources/
          β”œβ”€β”€ application.properties
          └── static/

50. What is Lombok and how does it help?

Answer:

Lombok is a Java library that reduces boilerplate code like getters/setters:

javaCopyEdit@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private Long id;
    private String name;
}

Just add it as a dependency and let it auto-generate code.