Spring

Spring

Top Interview Questions

About Spring

 

Spring Framework: An Overview

Spring is one of the most popular and widely used frameworks in the Java ecosystem. It provides a comprehensive programming and configuration model for modern Java-based enterprise applications. Spring simplifies Java development by promoting good design practices such as loose coupling, dependency injection, and aspect-oriented programming. It helps developers build robust, scalable, and maintainable applications while reducing boilerplate code and improving productivity.

Originally developed by Rod Johnson in 2002, Spring has evolved significantly over the years. Its primary goal was to address the complexity of developing enterprise-level applications using the traditional Enterprise JavaBeans (EJB) approach. Spring offers a lightweight alternative to EJB while maintaining enterprise capabilities such as transaction management, security, and integration with databases and messaging systems.

Spring has grown into a powerful ecosystem with numerous projects that complement its core capabilities, including Spring Boot, Spring Data, Spring Security, Spring Cloud, and more.


History of Spring Framework

The Spring Framework was introduced with the publication of Rod Johnson’s book, Expert One-on-One J2EE Design and Development, in 2002. The framework’s main motivation was to simplify Java EE development, which was often considered cumbersome and heavyweight.

Key milestones in Spring’s evolution include:

  • 2002: Spring Framework 1.0 is released, introducing Inversion of Control (IoC) and Dependency Injection (DI).

  • 2005: Spring 2.0 is released, adding features like XML-based configuration enhancements and Aspect-Oriented Programming (AOP) support.

  • 2009: Spring 3.0 introduces Java-based configuration and integration with RESTful web services.

  • 2014: Spring Boot is released, significantly simplifying the creation of production-ready Spring applications with minimal configuration.

  • 2018-2020: Spring 5.x introduces reactive programming support, functional programming capabilities, and full Java 8+ feature compatibility.

Today, Spring is the go-to framework for building enterprise-grade Java applications, microservices, and cloud-native solutions.


Core Features of Spring

The Spring Framework provides a wide range of features that make it indispensable for Java developers:

  1. Dependency Injection (DI) / Inversion of Control (IoC):
    Spring’s core principle is IoC, which allows objects to define their dependencies through configuration rather than instantiating them directly. This promotes loose coupling, easier testing, and better maintainability.

  2. Aspect-Oriented Programming (AOP):
    Spring allows separation of cross-cutting concerns such as logging, security, and transaction management using AOP. This enables cleaner code and better modularity.

  3. Transaction Management:
    Spring provides a consistent and declarative way to manage transactions, abstracting underlying implementations such as JDBC, JPA, and Hibernate.

  4. Data Access Integration:
    Spring seamlessly integrates with JDBC, JPA, Hibernate, MyBatis, and other data access technologies, reducing boilerplate code and handling resource management automatically.

  5. Model-View-Controller (MVC) Framework:
    Spring MVC is a web framework that supports RESTful services and traditional web applications. It separates business logic, presentation, and data access layers, promoting a clean architecture.

  6. Security:
    Spring Security offers authentication, authorization, and protection against common security vulnerabilities like CSRF and XSS.

  7. Integration with Enterprise Systems:
    Spring provides integration with messaging systems (JMS, Kafka), web services (SOAP/REST), and cloud-based solutions, making it suitable for modern enterprise applications.

  8. Lightweight and Modular:
    Spring’s modular architecture allows developers to use only the components they need, making applications lightweight and easy to maintain.


Spring Architecture

Spring’s architecture is designed in a modular way, consisting of several layers:

  1. Core Container:
    This layer provides the fundamental functionality of Spring, including IoC and DI. Key modules include:

    • Beans: Supports bean creation and management.

    • Core: Provides core functionalities such as object lifecycle and configuration.

    • Context: Offers access to application objects, similar to a JNDI registry.

    • Expression Language (SpEL): Enables querying and manipulating object graphs at runtime.

  2. Data Access/Integration Layer:
    This layer simplifies database operations and supports declarative transaction management. Key modules include:

    • JDBC: Simplifies database interactions.

    • ORM: Integrates with ORM frameworks like Hibernate, JPA.

    • JMS: Supports messaging.

    • Transactions: Offers programmatic and declarative transaction management.

  3. Web Layer:
    This layer provides comprehensive web application support, including RESTful services and MVC architecture.

    • Web: Basic web-oriented integration features.

    • Web MVC: Supports MVC architecture and REST APIs.

    • WebFlux: Supports reactive web applications for high-performance scenarios.

  4. AOP and Instrumentation Layer:
    Provides aspect-oriented programming features and support for class instrumentation.

  5. Test Layer:
    Spring includes testing support for JUnit and TestNG, helping developers create unit and integration tests efficiently.


Spring Modules

Spring has a rich ecosystem of modules designed for various use cases:

  1. Spring Boot:
    A key project in the Spring ecosystem, Spring Boot simplifies application setup by providing opinionated defaults, auto-configuration, embedded servers, and production-ready features.

  2. Spring Data:
    Provides an abstraction for data access, simplifying interaction with databases, NoSQL stores, and big data technologies.

  3. Spring Security:
    Offers robust authentication, authorization, and security features for web applications and microservices.

  4. Spring Cloud:
    Enables building cloud-native microservices, supporting distributed systems, configuration management, service discovery, and resilience patterns.

  5. Spring Batch:
    Supports batch processing of large volumes of data efficiently.

  6. Spring Integration:
    Facilitates integration with external systems using messaging, adapters, and workflows.

  7. Spring WebFlux:
    Enables reactive programming for asynchronous and non-blocking web applications.


Advantages of Using Spring

  1. Simplified Development: Spring reduces boilerplate code, especially for enterprise-level applications.

  2. Loose Coupling: DI promotes modular and maintainable code.

  3. Testability: Spring makes unit testing easier with mock objects and dependency injection.

  4. Flexibility: Spring is modular, allowing developers to use only the components needed.

  5. Integration: Supports integration with various technologies like databases, messaging systems, and web services.

  6. Scalability: Suitable for both monolithic and microservices architectures.


Use Cases of Spring

Spring is widely used across industries for building scalable and maintainable applications:

  1. Enterprise Applications:
    Spring is used to develop large-scale enterprise applications in finance, healthcare, and manufacturing. Its support for transactions, security, and data access is crucial for mission-critical systems.

  2. Web Applications:
    Spring MVC and Spring WebFlux are used to build both traditional and reactive web applications. Companies rely on Spring for their e-commerce platforms, banking portals, and SaaS applications.

  3. Microservices Architecture:
    With Spring Boot and Spring Cloud, developers can build microservices that are easy to deploy, maintain, and scale.

  4. Batch Processing:
    Spring Batch is used in scenarios like payroll processing, data migration, and ETL pipelines.

  5. Cloud Applications:
    Spring Cloud provides solutions for building cloud-native applications with distributed systems, service discovery, and configuration management.

 

Fresher Interview Questions

 

1. What is the Spring Framework?

Answer:
Spring is a lightweight, open-source framework for building Java-based enterprise applications. It provides comprehensive infrastructure support for developing Java applications. Spring focuses on loose coupling, dependency injection, and aspect-oriented programming to improve application modularity and testability.


2. What are the main features of the Spring Framework?

Answer:

  1. Dependency Injection (DI): Manages object dependencies automatically.

  2. Aspect-Oriented Programming (AOP): Separates cross-cutting concerns like logging and security.

  3. Transaction Management: Provides a consistent programming model across different transaction APIs.

  4. Spring MVC: Framework for building web applications.

  5. Integration: Easy integration with ORM frameworks like Hibernate, JPA.

  6. Lightweight and Modular: Can use parts of Spring independently.

  7. Testability: Makes unit testing easier through DI and mock objects.


3. What is Dependency Injection (DI)?

Answer:
Dependency Injection is a design pattern where the Spring container injects dependencies (objects required by a class) rather than the class creating them.

Types of DI:

  • Constructor-based DI: Dependencies are provided through a class constructor.

  • Setter-based DI: Dependencies are injected through setter methods.

Example (XML-based):

<bean id="car" class="com.example.Car">
    <property name="engine" ref="engine"/>
</bean>
<bean id="engine" class="com.example.Engine"/>

4. What is Inversion of Control (IoC)?

Answer:
IoC is a principle where the control of object creation and management is transferred from the application to the Spring container. DI is one implementation of IoC.


5. What are the different types of Spring configuration?

Answer:

  1. XML-based configuration – Traditional way using applicationContext.xml.

  2. Annotation-based configuration – Using annotations like @Component, @Autowired.

  3. Java-based configuration – Using @Configuration and @Bean classes.


6. What is the difference between BeanFactory and ApplicationContext?

Answer:

Feature BeanFactory ApplicationContext
Type Interface Interface (extends BeanFactory)
Object Creation Lazy initialization Eager initialization
Features Basic DI Advanced features (AOP, Event Handling, Internationalization)
Usage Lightweight apps Enterprise apps

7. What are Spring Beans?

Answer:
Beans are objects managed by the Spring IoC container. Each bean is created, initialized, and managed by Spring.

Bean Scopes:

  • Singleton: Single instance (default).

  • Prototype: New instance every time requested.

  • Request: One per HTTP request (web apps).

  • Session: One per HTTP session.

  • Application: Single instance per ServletContext.


8. What is Spring MVC?

Answer:
Spring MVC is a Model-View-Controller framework for building web applications.

  • Model: Represents data and business logic.

  • View: Presentation layer (JSP, Thymeleaf).

  • Controller: Handles requests and maps them to the service layer.


9. What are the advantages of Spring MVC?

Answer:

  1. Loose coupling between layers.

  2. Clean separation of responsibilities.

  3. Supports multiple view technologies.

  4. Easy integration with ORM frameworks.

  5. Annotation-driven programming.


10. What are the main annotations in Spring?

Answer:

  • @Component – Marks a class as a Spring component.

  • @Controller – Marks a class as a Spring MVC controller.

  • @Service – Marks a service class.

  • @Repository – Marks a DAO/repository class.

  • @Autowired – Injects a dependency automatically.

  • @Qualifier – Specifies which bean to inject when multiple exist.

  • @Configuration – Marks a Java class as a configuration class.

  • @Bean – Declares a bean in a configuration class.


11. What is AOP (Aspect-Oriented Programming)?

Answer:
AOP allows separation of cross-cutting concerns like logging, security, and transaction management.

Terminologies:

  • Aspect: Module containing cross-cutting concern.

  • Join Point: Specific point in program execution (e.g., method call).

  • Advice: Action taken at a join point (Before, After, Around).

  • Pointcut: Expression defining where advice should be applied.

  • Weaving: Linking aspects with target objects.


12. What are the types of advice in Spring AOP?

Answer:

  1. Before Advice: Runs before method execution.

  2. After Advice: Runs after method execution, regardless of outcome.

  3. After Returning: Runs after successful method execution.

  4. After Throwing: Runs if method throws an exception.

  5. Around Advice: Runs before and after method execution, allowing custom behavior.


13. What is the difference between @Component, @Service, @Controller, and @Repository?

Answer:

Annotation Layer Purpose
@Component General Generic bean
@Service Service Business logic layer
@Controller Web Handles web requests
@Repository DAO Data access layer, handles database exceptions

14. What is Spring Boot?

Answer:
Spring Boot is an opinionated framework on top of Spring to simplify configuration, setup, and deployment of Spring applications. Features include:

  • Auto-configuration.

  • Embedded servers (Tomcat, Jetty).

  • Starter dependencies for easy setup.

  • Production-ready metrics and monitoring.


15. What are the advantages of Spring Boot over Spring?

Answer:

  1. Minimal configuration required.

  2. Rapid development.

  3. Embedded web server.

  4. Simplified dependency management with starters.

  5. Microservices support out-of-the-box.


16. What are Spring Data and Spring JPA?

Answer:

  • Spring Data: Provides abstraction for data access and reduces boilerplate code.

  • Spring JPA: Integrates Java Persistence API (JPA) with Spring for ORM support.

Example: Using CrudRepository for CRUD operations.


17. What is the difference between @Autowired and @Inject?

Answer:

  • @Autowired – Spring-specific annotation for DI.

  • @Inject – Standard Java EE annotation (JSR-330) for DI.

Both achieve the same purpose, but @Autowired supports required=false and Spring-specific features.


18. What is the difference between @RequestParam and @PathVariable in Spring MVC?

Answer:

  • @RequestParam – Extracts query parameters from the URL.

  • @PathVariable – Extracts values from URI templates.

Example:

@GetMapping("/user/{id}")
public String getUser(@PathVariable int id, @RequestParam String name)

19. What is Spring Transaction Management?

Answer:
Spring provides a consistent abstraction for managing transactions in Java, which can be applied declaratively using @Transactional annotation or programmatically using TransactionTemplate.


20. What are the advantages of Spring?

Answer:

  1. Loose coupling and modularity.

  2. Easy testing and mocking.

  3. Supports declarative programming.

  4. Reduces boilerplate code.

  5. Scalable for enterprise applications.


21. Explain the Spring Bean lifecycle.

Answer:

  1. Bean instantiation.

  2. Populate properties (DI).

  3. BeanNameAware, BeanFactoryAware methods.

  4. BeanPostProcessor before initialization.

  5. Initialization (@PostConstruct or afterPropertiesSet).

  6. BeanPostProcessor after initialization.

  7. Bean ready for use.

  8. Destruction (@PreDestroy or destroy() method).


22. What is the difference between @ComponentScan and context:component-scan?

Answer:

  • @ComponentScan – Annotation-based configuration for scanning beans.

  • <context:component-scan> – XML-based configuration.


23. What is Spring Expression Language (SpEL)?

Answer:
SpEL is a powerful expression language for querying and manipulating objects at runtime.
Example:

@Value("#{2 * 3}")
private int value; // value = 6

24. How does Spring handle exceptions?

Answer:

  • Spring provides @ExceptionHandler in controllers for custom handling.

  • ControllerAdvice can handle exceptions globally.

  • Spring also wraps database exceptions into DataAccessException.


25. What are some common interview scenario questions?

Examples:

  • “How would you implement logging across multiple services?” → Use AOP.

  • “How would you handle transactions in a banking app?” → Use @Transactional.

  • “How can Spring help reduce boilerplate JDBC code?” → Use Spring JDBC Template.


26. What is the difference between @Component, @Service, and @Repository in real-time scenarios?

Answer:

  • @Component – General-purpose bean. Used when there’s no specific role.

  • @Service – Represents business logic. Example: PaymentService handles payments.

  • @Repository – Handles data access and can automatically translate SQL exceptions into Spring exceptions. Example: UserRepository accessing MySQL.

Scenario:
If your project has a layered architecture:

  • DAO layer → @Repository

  • Service layer → @Service

  • Controller → @Controller


27. What is Spring Boot Starter?

Answer:
Starters are dependency descriptors that simplify Maven or Gradle configuration by providing a pre-configured set of dependencies.

Example:

  • spring-boot-starter-web → Includes Spring MVC, embedded Tomcat, Jackson for JSON.

  • spring-boot-starter-data-jpa → Includes Spring Data JPA, Hibernate.

Scenario:
Instead of adding 10+ dependencies manually, you just include the starter.


28. Explain Spring Boot Auto-Configuration.

Answer:
Spring Boot automatically configures beans based on dependencies in the classpath.

Example:
If spring-boot-starter-data-jpa is on the classpath, Spring Boot automatically configures EntityManagerFactory and DataSource.

Scenario:
You don’t need to write applicationContext.xml or manually configure beans.


29. What is @SpringBootApplication?

Answer:
@SpringBootApplication is a composite annotation combining:

  • @Configuration → Java-based config

  • @EnableAutoConfiguration → Auto configuration

  • @ComponentScan → Scans for components

Scenario:
By adding this annotation on your main class, Spring Boot knows to scan, configure, and bootstrap your application.


30. What is Spring Security?

Answer:
Spring Security is a powerful authentication and authorization framework for Java applications.

Features:

  • Authentication (login, OAuth2, JWT)

  • Authorization (roles, permissions)

  • Protection against CSRF and XSS attacks

  • Method-level security (@PreAuthorize)


31. Difference between Authentication and Authorization

Answer:

Term Definition Example
Authentication Verifying who the user is Login with username/password
Authorization Verifying what the user can access User role ‘ADMIN’ can delete records

32. What is @Transactional in Spring?

Answer:
@Transactional is used to declare transactional boundaries in Spring.

Scenario:

@Service
public class AccountService {
    @Transactional
    public void transferMoney(Account from, Account to, double amount) {
        debit(from, amount);
        credit(to, amount);
    }
}

If credit() fails, Spring will rollback the transaction, ensuring data consistency.


33. What is Spring Data JPA Repository?

Answer:
Spring Data JPA provides pre-built repository interfaces like:

  • CrudRepository → Basic CRUD operations

  • JpaRepository → Advanced operations, pagination, sorting

Scenario:
Instead of writing SQL, you can define:

public interface UserRepository extends JpaRepository<User, Long> {
    List<User> findByLastName(String lastName);
}

34. Difference between @RestController and @Controller

Answer:

Annotation Description
@Controller Returns view names (JSP, Thymeleaf)
@RestController Returns JSON/XML directly (used in REST APIs)

Scenario:
For REST APIs in Spring Boot, always use @RestController.


35. What is Spring Actuator?

Answer:
Spring Actuator provides production-ready features like:

  • Health check (/actuator/health)

  • Metrics (/actuator/metrics)

  • Environment info (/actuator/env)

Scenario:
Useful in microservices for monitoring and management.


36. Difference between @ControllerAdvice and @ExceptionHandler

Answer:

  • @ExceptionHandler → Handles exceptions in a specific controller.

  • @ControllerAdvice → Handles exceptions globally across all controllers.

Scenario:

@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleAll(Exception e) {
        return new ResponseEntity<>("Error: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

37. What is Spring Profiles?

Answer:
Spring Profiles allows you to group beans or configurations for different environments (dev, test, prod).

Example:

@Profile("dev")
@Bean
public DataSource devDataSource() { ... }

Scenario:
You can switch profiles using:

spring.profiles.active=dev

38. Difference between BeanFactory and ApplicationContext in real-time

Answer:

  • BeanFactory → Lightweight, lazy initialization. Good for memory-sensitive apps.

  • ApplicationContext → Eager initialization, supports AOP, event handling. Good for enterprise applications.

Scenario:
For a web application with logging and transaction management → ApplicationContext is preferred.


39. What is Spring’s Environment Abstraction?

Answer:
Spring provides Environment interface to access properties and profiles.

Example:

@Value("${app.name}")
private String appName;

Scenario:
Useful to read application.properties or environment variables dynamically.


40. What are Spring Beans scopes and when to use them?

Answer:

Scope Description Use Case Example
Singleton One instance per Spring container Service layer
Prototype New instance each request Stateful beans
Request One per HTTP request Web controllers
Session One per HTTP session User session data
Application One per ServletContext Shared resources

41. Difference between @RequestBody and @ResponseBody

Answer:

  • @RequestBody → Maps HTTP request JSON to Java object.

  • @ResponseBody → Converts Java object to HTTP response JSON.

Scenario:

@PostMapping("/user")
public User createUser(@RequestBody User user) { return user; }

42. How to implement logging using Spring AOP?

Answer:

@Aspect
@Component
public class LoggingAspect {
    @Before("execution(* com.example.service.*.*(..))")
    public void logBefore(JoinPoint joinPoint) {
        System.out.println("Executing: " + joinPoint.getSignature().getName());
    }
}

Scenario:
Logs every method in the service layer without modifying business code.


43. What is the difference between @EnableAutoConfiguration and manual configuration?

Answer:

  • @EnableAutoConfiguration → Automatically configures Spring beans based on dependencies.

  • Manual configuration → You have to explicitly define beans using @Bean or XML.

Scenario:
For rapid development → Auto-configuration is preferred.


44. What is the difference between @Qualifier and primary beans?

Answer:

  • @Qualifier → Specifies which bean to inject when multiple beans of the same type exist.

  • @Primary → Marks one bean as default when multiple beans exist.


45. Explain Spring Boot DevTools

Answer:
Spring Boot DevTools provides developer productivity features:

  • Automatic restart

  • Live reload

  • H2 console support

Scenario:
During development, DevTools reduces manual restarts and improves feedback.


46. Difference between Spring Boot and Spring Framework

Feature Spring Framework Spring Boot
Configuration Manual Auto-configuration
Web server External server required Embedded server
Deployment WAR file Executable JAR
Speed Slower setup Rapid setup

47. What is Spring Cloud?

Answer:
Spring Cloud provides tools for building distributed, cloud-native microservices. Features include:

  • Config server

  • Eureka service registry

  • Load balancing

  • Circuit breakers

Scenario:
Used when building microservices architecture with Spring Boot.


48. What is @Conditional annotation?

Answer:
@Conditional allows conditional bean registration.

Scenario:

@Bean
@Conditional(OnPropertyCondition.class)
public MyBean myBean() { return new MyBean(); }

The bean is registered only if a condition is true.


49. What is Spring RestTemplate?

Answer:
RestTemplate is used to consume REST APIs in Spring.

Example:

RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.getForObject("https://api.example.com/users", String.class);

50. What is WebClient in Spring 5?

Answer:
WebClient is the reactive replacement for RestTemplate.

  • Supports async requests.

  • Part of Spring WebFlux.


51. Difference between Spring MVC and Spring WebFlux

Feature Spring MVC Spring WebFlux
Programming Model Servlet-based Reactive, non-blocking
Thread Model One thread per request Event-loop, async
Use Case Standard web apps High-performance, reactive apps

52. How to test Spring applications?

Answer:

  • Unit testing: Using @MockBean and Mockito

  • Integration testing: Using @SpringBootTest

  • Web layer testing: Using @WebMvcTest

Scenario:

@SpringBootTest
class UserServiceTest {
    @Autowired
    private UserService userService;
}

53. What is Spring JMS?

Answer:
Spring JMS allows integration with message brokers (ActiveMQ, RabbitMQ) for asynchronous communication.

Scenario:
Order service sends a message → Inventory service consumes the message asynchronously.


54. What is Spring Cache?

Answer:
Spring Cache allows automatic caching of method results to improve performance.

Example:

@Cacheable("users")
public User getUser(Long id) { ... }

55. Real-time scenario: How would you design a banking microservice using Spring Boot?

Answer:

  1. Layers: Controller, Service, Repository

  2. Transactions: Use @Transactional for money transfers

  3. Security: Spring Security with roles (Admin, User)

  4. Logging: Spring AOP for auditing

  5. REST APIs: Use @RestController and DTOs

  6. Database: Spring Data JPA

  7. Caching: Spring Cache for frequently accessed accounts

  8. Monitoring: Spring Boot Actuator

 

Experienced Interview Questions

 

1. What is Spring Framework and why is it still relevant for enterprise applications?

Answer:
Spring is a lightweight, open-source Java framework for building robust, modular, and maintainable applications.
Relevance for experienced developers:

  • Supports enterprise-grade applications.

  • Enables microservices architecture with Spring Boot and Spring Cloud.

  • Provides integration with modern tools (REST APIs, messaging, security).

  • Enhances developer productivity with DI, AOP, and modularization.

Scenario: Migrating a legacy Java EE project to Spring for better testability and modularity.


2. What is Dependency Injection (DI) and how have you applied it in real projects?

Answer:
DI is a design pattern where dependencies are injected by the container, not created by the class itself.

Real-time application:

  • Service layer depends on DAO layer.

  • Example using Constructor-based DI for immutability:

@Service
public class PaymentService {
    private final PaymentRepository repo;

    @Autowired
    public PaymentService(PaymentRepository repo) {
        this.repo = repo;
    }
}
  • Advantage: Easier unit testing using mock repositories.


3. Explain Spring Bean scopes and their practical usage

Answer:

Scope Definition Real-time Usage
Singleton One instance per container Most services, repositories
Prototype New instance every request Stateless helper beans
Request One per HTTP request Controllers, request-bound data
Session One per HTTP session User session beans
Application One per ServletContext Shared application resources

Scenario: Use singleton for UserService but prototype for PDF report generator.


4. What is the difference between BeanFactory and ApplicationContext in large projects?

Answer:

  • BeanFactory → Lightweight, lazy initialization.

  • ApplicationContext → Enterprise features: AOP, internationalization, events, eager initialization.

Scenario:
In microservices, we always prefer ApplicationContext for transaction management and event handling.


5. How have you implemented Spring AOP in your projects?

Answer:
Spring AOP allows cross-cutting concerns like logging, security, and auditing to be implemented without cluttering business logic.

Example:

@Aspect
@Component
public class AuditAspect {
    @AfterReturning("execution(* com.example.service.*.*(..))")
    public void logAfter(JoinPoint joinPoint) {
        System.out.println("Executed method: " + joinPoint.getSignature().getName());
    }
}

Scenario: Auditing all sensitive financial transactions.


6. Difference between XML, Annotation, and Java-based configuration

Answer:

Configuration Type Usage Scenario Example
XML Legacy applications <bean id="service" class="..."/>
Annotation Modern apps, reduces boilerplate @Service, @Autowired
Java-based (@Configuration) Type-safe, IDE-friendly @Bean public DataSource dataSource() {}

Scenario: In microservices, Java-based configuration is preferred for clarity.


7. How do you implement transaction management in Spring?

Answer:
Options:

  1. Declarative: @Transactional

  2. Programmatic: TransactionTemplate

Scenario: In a banking app:

@Transactional
public void transferMoney(Account from, Account to, double amount) {
    debit(from, amount);
    credit(to, amount);
}
  • Ensures rollback if any step fails.


8. Explain Spring Boot Auto-Configuration and its limitations

Answer:

  • Auto-configuration detects classpath dependencies and creates beans automatically.

  • Limitation: Overriding default configurations may require @ConditionalOnMissingBean.

Scenario: Default DataSource auto-configured, but custom connection pool required manual override.


9. What are Spring Profiles and how do you manage multiple environments?

Answer:

  • Profiles separate beans and configurations for dev, test, prod environments.

@Profile("dev")
@Bean
public DataSource devDataSource() { ... }
  • Active profile: spring.profiles.active=prod

Scenario: Use H2 for dev and PostgreSQL for prod.


10. How do you implement caching in Spring?

Answer:

  • Use @EnableCaching at configuration level.

  • Use @Cacheable, @CachePut, and @CacheEvict.

Example:

@Cacheable("users")
public User getUser(Long id) { ... }

Scenario: Frequently accessed user details are cached to reduce DB hits.


11. How do you secure REST APIs using Spring Security?

Answer:

  • Use JWT or OAuth2 for authentication.

  • Use method-level security with @PreAuthorize and @Secured.

Scenario:

@PreAuthorize("hasRole('ADMIN')")
@PostMapping("/users")
public void createUser(User user) { ... }
  • Only users with ADMIN role can create new users.


12. Difference between @Component, @Service, @Repository in enterprise apps

Answer:

  • @Component – Generic bean.

  • @Service – Business layer logic.

  • @Repository – DAO layer, exception translation.

Scenario:
All database access logic is wrapped in @Repository to translate SQL exceptions to Spring DataAccessException.


13. How do you handle exceptions in Spring Boot REST APIs?

Answer:

  • Controller-level: @ExceptionHandler

  • Global-level: @ControllerAdvice

  • Example:

@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<String> handleNotFound(ResourceNotFoundException e) {
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(e.getMessage());
    }
}
  • Ensures uniform error responses across microservices.


14. How do you manage database migrations in Spring Boot projects?

Answer:

  • Use Flyway or Liquibase.

  • Auto-executed on startup to maintain versioned DB schema.

Scenario: Avoids inconsistencies when deploying to multiple environments.


15. Explain Spring Data JPA and custom repository implementations

Answer:

  • Provides CrudRepository and JpaRepository.

  • Supports query methods, @Query annotation, and custom implementations.

Example:

@Query("SELECT u FROM User u WHERE u.active = true")
List<User> findActiveUsers();

Scenario: Custom queries for reporting and analytics.


16. How do you handle batch processing in Spring?

Answer:

  • Use Spring Batch for large-scale jobs.

  • Supports chunk-based processing, retry mechanisms, and scheduling.

Scenario: Processing millions of transactions overnight.


17. Difference between Spring MVC and Spring WebFlux

Feature Spring MVC (Blocking) Spring WebFlux (Non-blocking)
Model Servlet-based synchronous Reactive and async
Threading One thread per request Event-loop, reactive
Use Case Standard web apps High throughput microservices

18. How do you integrate Spring with messaging systems?

Answer:

  • Spring JMS: For ActiveMQ or RabbitMQ.

  • Spring Kafka: For Kafka topics.

  • Scenario: Microservices communicating asynchronously for order processing.


19. What is Spring Cloud and its components?

Answer:
Spring Cloud helps in building cloud-native microservices:

  • Eureka: Service registry

  • Ribbon: Client-side load balancing

  • Zuul/Gateway: API gateway

  • Config Server: Centralized configuration

Scenario: Microservices architecture with dynamic service discovery.


20. How do you monitor and manage Spring Boot applications in production?

Answer:

  • Spring Boot Actuator: Health, metrics, environment.

  • Micrometer: Integrates with Prometheus/Grafana.

  • Scenario: Monitor memory, CPU, DB connections in real-time.


21. How do you implement reactive programming in Spring?

Answer:

  • Use Spring WebFlux with Mono and Flux.

  • Supports non-blocking I/O for high concurrency applications.

Example:

@GetMapping("/users")
public Flux<User> getAllUsers() { ... }

22. How do you implement pagination and sorting with Spring Data JPA?

Answer:

  • Use Pageable and Page objects:

Page<User> users = userRepository.findAll(PageRequest.of(0, 10, Sort.by("name")));
  • Scenario: Large dataset reporting in enterprise apps.


23. How do you handle circular dependencies in Spring?

Answer:

  • Solution: Use @Lazy or constructor injection refactoring.

  • Avoid field injection when possible.


24. Explain conditional bean creation in Spring

Answer:

  • @Conditional, @Profile, or @ConditionalOnProperty

  • Scenario: Create bean only in dev environment or if a property exists.


25. How do you implement internationalization (i18n) in Spring Boot?

Answer:

  • Use ResourceBundleMessageSource and LocaleResolver.

  • Scenario: Multi-country applications with language-specific messages.


26. Difference between RestTemplate and WebClient

Feature RestTemplate (Blocking) WebClient (Non-blocking)
Blocking Yes No
Reactive No Yes
Performance Lower under load Higher under high concurrency

27. How do you implement versioning for REST APIs?

Answer:

  • URL versioning: /api/v1/users

  • Header versioning: X-API-VERSION: 1

  • Scenario: Maintain backward compatibility with clients.


28. How do you handle file upload in Spring Boot?

Answer:

  • Use MultipartFile with @RequestParam.

  • Scenario: Large files handled asynchronously or stored in cloud storage.


29. How do you implement global configuration properties?

Answer:

  • Use @ConfigurationProperties or @Value.

  • Scenario: Externalized configuration for microservices.


30. How do you implement scheduled tasks?

Answer:

  • Use @EnableScheduling and @Scheduled(cron = "...").

  • Scenario: Data cleanup, report generation, periodic polling.


31. How do you integrate Spring with caching systems?

Answer:

  • Redis, EhCache, Caffeine

  • Use @Cacheable and @CacheEvict annotations

  • Scenario: Frequently accessed data like product catalog.


32. How do you handle session management in Spring Security?

Answer:

  • Strategies: STATELESS (JWT), STATEFUL (HTTP session)

  • Prevent session fixation, concurrent logins, timeout.


33. How do you implement role-based access control?

Answer:

  • @PreAuthorize("hasRole('ADMIN')")

  • Scenario: Different roles (Admin/User/Manager) for API endpoints.


34. How do you implement OAuth2 authentication in Spring Boot?

Answer:

  • Use spring-security-oauth2-client

  • Supports Google/Facebook login

  • Scenario: Single Sign-On in enterprise portals.


35. How do you implement API rate limiting?

Answer:

  • Use Spring Boot Filter/Interceptor or Bucket4j

  • Scenario: Prevent abuse of public REST APIs.


36. How do you implement multi-tenancy in Spring Boot?

Answer:

  • Schema-based, Database-based, or Discriminator-based

  • Scenario: SaaS applications serving multiple clients in a single DB.


37. How do you optimize performance in Spring applications?

Answer:

  • Use caching, lazy loading, connection pooling, pagination, async processing

  • Monitor with Actuator + Micrometer

  • Scenario: Reduce DB hits in high traffic services.


38. How do you implement distributed transactions?

Answer:

  • Use Spring Boot + JTA/XA Transactions or Saga Pattern

  • Scenario: Order service updates inventory, payment, and shipping across microservices.


39. How do you implement asynchronous processing?

Answer:

  • Use @EnableAsync and @Async

  • Scenario: Send emails without blocking user requests.


40. How do you implement messaging with RabbitMQ/Kafka?

Answer:

  • Producer/Consumer with @RabbitListener or @KafkaListener

  • Scenario: Event-driven architecture for microservices.


41. How do you test Spring Boot applications?

Answer:

  • Unit testing: Mockito, @MockBean

  • Integration testing: @SpringBootTest

  • Web layer: @WebMvcTest

  • Scenario: Testing REST endpoints without hitting production DB.


42. How do you implement graceful shutdown in Spring Boot?

Answer:

  • spring.lifecycle.timeout-per-shutdown-phase

  • Scenario: Finish ongoing requests before shutdown.


43. How do you handle circular dependencies in Spring Boot?

Answer:

  • Prefer constructor injection

  • Use @Lazy annotation to break circular reference


44. How do you secure microservices with Spring Cloud Gateway?

Answer:

  • Use JWT filters, OAuth2, role-based access

  • Scenario: API Gateway handles authentication for multiple services.


45. How do you implement reactive data access?

Answer:

  • Use Spring Data R2DBC or MongoDB reactive repositories

  • Scenario: High throughput non-blocking database calls.


46. How do you implement global exception handling in microservices?

Answer:

  • Use @ControllerAdvice across services

  • Scenario: Consistent error responses across APIs.


47. How do you manage configuration for multiple microservices?

Answer:

  • Use Spring Cloud Config Server with Git

  • Scenario: Centralized property management.


48. How do you implement service discovery?

Answer:

  • Use Eureka server

  • Scenario: Dynamically discover instances in microservices architecture.


49. How do you implement circuit breaker in Spring Cloud?

Answer:

  • Use Resilience4j or Hystrix

  • Scenario: Prevent cascading failures in dependent services.


50. How do you implement distributed tracing?

Answer:

  • Use Spring Cloud Sleuth + Zipkin

  • Scenario: Track requests across microservices for debugging and monitoring.


51. How do you implement API documentation?

Answer:

  • Use Springfox Swagger or Springdoc OpenAPI

  • Scenario: REST APIs easily discoverable and testable.


52. How do you handle configuration reload at runtime?

Answer:

  • Use Spring Cloud Config + Spring Cloud Bus

  • Scenario: Update properties without restarting microservices.


53. How do you implement health checks in production?

Answer:

  • Spring Boot Actuator /actuator/health

  • Scenario: Monitor DB, messaging, disk space, and dependencies.


54. How do you implement graceful degradation?

Answer:

  • Use Fallback methods with Resilience4j

  • Scenario: Service fails → fallback response ensures UX continuity.


55. Real-time scenario: Designing a banking microservice

Answer:

  1. Layers: Controller, Service, Repository

  2. Transaction management: @Transactional

  3. Security: OAuth2 + JWT + Role-based access

  4. Caching: Redis for frequent queries

  5. Async processing: Email notifications, SMS alerts

  6. Event-driven: Kafka for audit logs

  7. Monitoring: Actuator + Prometheus

  8. Testing: Unit and integration testing with mocks and embedded DB