Spring Basics for Interview

Yash PatariYash Patari
3 min read

Most Asked Java & Spring Boot Interview Questions at Info Edge (with Detailed Answers)


1. What is Spring Boot, and how does it differ from the Spring Framework?

Answer: Spring Boot is an extension of the Spring Framework that simplifies the process of creating stand-alone, production-grade Spring applications. It reduces boilerplate code and configuration by providing:

  • Auto-Configuration: Automatically configures your application based on dependencies.

  • Embedded Servers: Uses Tomcat, Jetty, or Undertow embedded in the app.

  • Starter POMs: Provides dependencies grouped by functionality.

  • Production-Ready Features: Metrics, health checks, externalized config via Spring Boot Actuator.

Difference from Spring Framework: Spring requires manual configuration of dependencies, servers, and setups, while Spring Boot minimizes this effort with sensible defaults.


2. Explain Dependency Injection and Inversion of Control.

Answer:

  • Inversion of Control (IoC): It’s a design principle where the control of object creation and dependency management is transferred from the application code to the Spring container.

  • Dependency Injection (DI): It is a pattern used to implement IoC. Objects are provided their dependencies instead of creating them manually.

Types in Spring:

  • Constructor Injection

  • Setter Injection

  • Field Injection (not recommended for testing)

Example:

@Component
public class Car {
    private final Engine engine;
    @Autowired
    public Car(Engine engine) {
        this.engine = engine;
    }
}

3. What are the different scopes of Spring Beans?

Answer: Spring defines several bean scopes:

  • Singleton (default): One instance per Spring container.

  • Prototype: New instance each time it's requested.

  • Request: One instance per HTTP request (web only).

  • Session: One instance per HTTP session.

  • Application: One instance per ServletContext.

  • Websocket: One instance per WebSocket session.

Usage:

@Bean
@Scope("prototype")
public MyBean myBean() {
    return new MyBean();
}

4. How does Spring Boot manage application properties and profiles?

Answer:

  • Uses application.properties or application.yml to externalize configuration.

  • Profiles like dev, test, prod can be defined using:

spring.profiles.active=dev
  • Profile-specific files: application-dev.properties

  • Can use @Profile("dev") to restrict beans to certain environments.


5. What is the purpose of the @SpringBootApplication annotation?

Answer: It is a convenience annotation that combines:

  • @Configuration: Marks the class as a source of bean definitions.

  • @EnableAutoConfiguration: Tells Spring Boot to start auto-configuration.

  • @ComponentScan: Scans for components in the package and its sub-packages.

Example:

@SpringBootApplication
public class MyApp {
    public static void main(String[] args) {
        SpringApplication.run(MyApp.class, args);
    }
}

6. How do you handle exceptions in Spring Boot applications?

Answer: Use:

  • @ControllerAdvice: Global exception handler.

  • @ExceptionHandler: Handles specific exceptions.

Example:

@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<String> handleNotFound(ResourceNotFoundException ex) {
        return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
    }
}

7. What is the difference between @Controller and @RestController?

Answer:

  • @Controller: Used to define web controllers; requires @ResponseBody to return data.

  • @RestController: Combines @Controller and @ResponseBody, suitable for REST APIs.

Example:

@RestController
public class MyController {
    @GetMapping("/hello")
    public String sayHello() {
        return "Hello, World!";
    }
}

8. Explain the use of Spring Boot Actuator.

Answer: Spring Boot Actuator provides endpoints to monitor and manage your app:

  • /actuator/health

  • /actuator/metrics

  • /actuator/env

Add to pom.xml:

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

Enable endpoints in application.properties:

management.endpoints.web.exposure.include=*

9. How do you implement pagination and sorting in Spring Data JPA?

Answer: Use PagingAndSortingRepository or JpaRepository:

Page<User> findByAge(int age, Pageable pageable);

Usage:

PageRequest pageRequest = PageRequest.of(0, 10, Sort.by("name"));
Page<User> users = userRepository.findByAge(25, pageRequest);

10. What are the differences between CrudRepository and JpaRepository?

Answer:

  • CrudRepository: Basic CRUD operations.

  • JpaRepository: Extends CrudRepository, adds:

    • Batch operations

    • Pagination and Sorting support

    • flush(), saveAndFlush(), deleteInBatch() methods

Use JpaRepository when: You need full JPA functionality with additional features beyond basic CRUD.


0
Subscribe to my newsletter

Read articles from Yash Patari directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Yash Patari
Yash Patari

Hi, I am Yash Patari, a passionate backend Java developer. πŸš€ Backend Engineer | Cloud-Native Systems | Innovation & Scale I specialize in building robust, scalable, and secure backend systems using Java (Spring Boot), PostgreSQL, Docker, AWS, Elasticsearch, Solr, and Kubernetes. My work focuses on performance tuning, system design, and solving real-world problems with innovative, cloud-native solutions. πŸ”§ Key Expertise πŸ’» Languages: Java, SQL, JavaScript 🌐 Frameworks: Spring Boot, Hibernate, JUnit πŸ—„οΈ Databases: PostgreSQL, MySQL, MongoDB ☁️ Cloud & DevOps: AWS (S3, EC2, Lambda), Docker, Kubernetes, Jenkins, Git πŸ” Search & Indexing: Apache Solr 🧱 Architecture: Microservices, Monoliths, REST APIs, Event-Driven Design πŸ” Security: OAuth2, JWT, File Encryption, Presigned URLs πŸ“¦ Data Handling: Large File Uploads (5GB–5TB), Excel Bulk Ops, Delegation Logic πŸ› οΈ Tools: IntelliJ, Postman, Maven, Gradle, GitHub, Bitbucket πŸš€ Practices: Agile, CI/CD, System Design, Performance Tuning πŸ’‘ Delivered: Scalable microservices for 10K+ users & millions of tasks Secure file uploads (5GB–5TB) via presigned S3 URLs Solr-integrated encrypted data search Refactored APIs adopted by 100+ B2B clients πŸ† Best Developer @ Sirion | 4⭐ CodeChef | LeetCode Knight I love experimenting with new tech and building smarter, faster, and more resilient systems.