Top Interview Questions
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.
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.
The Spring Framework provides a wide range of features that make it indispensable for Java developers:
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.
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.
Transaction Management:
Spring provides a consistent and declarative way to manage transactions, abstracting underlying implementations such as JDBC, JPA, and Hibernate.
Data Access Integration:
Spring seamlessly integrates with JDBC, JPA, Hibernate, MyBatis, and other data access technologies, reducing boilerplate code and handling resource management automatically.
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.
Security:
Spring Security offers authentication, authorization, and protection against common security vulnerabilities like CSRF and XSS.
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.
Lightweight and Modular:
Spring’s modular architecture allows developers to use only the components they need, making applications lightweight and easy to maintain.
Spring’s architecture is designed in a modular way, consisting of several layers:
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.
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.
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.
AOP and Instrumentation Layer:
Provides aspect-oriented programming features and support for class instrumentation.
Test Layer:
Spring includes testing support for JUnit and TestNG, helping developers create unit and integration tests efficiently.
Spring has a rich ecosystem of modules designed for various use cases:
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.
Spring Data:
Provides an abstraction for data access, simplifying interaction with databases, NoSQL stores, and big data technologies.
Spring Security:
Offers robust authentication, authorization, and security features for web applications and microservices.
Spring Cloud:
Enables building cloud-native microservices, supporting distributed systems, configuration management, service discovery, and resilience patterns.
Spring Batch:
Supports batch processing of large volumes of data efficiently.
Spring Integration:
Facilitates integration with external systems using messaging, adapters, and workflows.
Spring WebFlux:
Enables reactive programming for asynchronous and non-blocking web applications.
Simplified Development: Spring reduces boilerplate code, especially for enterprise-level applications.
Loose Coupling: DI promotes modular and maintainable code.
Testability: Spring makes unit testing easier with mock objects and dependency injection.
Flexibility: Spring is modular, allowing developers to use only the components needed.
Integration: Supports integration with various technologies like databases, messaging systems, and web services.
Scalability: Suitable for both monolithic and microservices architectures.
Spring is widely used across industries for building scalable and maintainable applications:
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.
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.
Microservices Architecture:
With Spring Boot and Spring Cloud, developers can build microservices that are easy to deploy, maintain, and scale.
Batch Processing:
Spring Batch is used in scenarios like payroll processing, data migration, and ETL pipelines.
Cloud Applications:
Spring Cloud provides solutions for building cloud-native applications with distributed systems, service discovery, and configuration management.
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.
Answer:
Dependency Injection (DI): Manages object dependencies automatically.
Aspect-Oriented Programming (AOP): Separates cross-cutting concerns like logging and security.
Transaction Management: Provides a consistent programming model across different transaction APIs.
Spring MVC: Framework for building web applications.
Integration: Easy integration with ORM frameworks like Hibernate, JPA.
Lightweight and Modular: Can use parts of Spring independently.
Testability: Makes unit testing easier through DI and mock objects.
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"/>
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.
Answer:
XML-based configuration – Traditional way using applicationContext.xml.
Annotation-based configuration – Using annotations like @Component, @Autowired.
Java-based configuration – Using @Configuration and @Bean classes.
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 |
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.
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.
Answer:
Loose coupling between layers.
Clean separation of responsibilities.
Supports multiple view technologies.
Easy integration with ORM frameworks.
Annotation-driven programming.
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.
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.
Answer:
Before Advice: Runs before method execution.
After Advice: Runs after method execution, regardless of outcome.
After Returning: Runs after successful method execution.
After Throwing: Runs if method throws an exception.
Around Advice: Runs before and after method execution, allowing custom behavior.
@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 |
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.
Answer:
Minimal configuration required.
Rapid development.
Embedded web server.
Simplified dependency management with starters.
Microservices support out-of-the-box.
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.
@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.
@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)
Answer:
Spring provides a consistent abstraction for managing transactions in Java, which can be applied declaratively using @Transactional annotation or programmatically using TransactionTemplate.
Answer:
Loose coupling and modularity.
Easy testing and mocking.
Supports declarative programming.
Reduces boilerplate code.
Scalable for enterprise applications.
Answer:
Bean instantiation.
Populate properties (DI).
BeanNameAware, BeanFactoryAware methods.
BeanPostProcessor before initialization.
Initialization (@PostConstruct or afterPropertiesSet).
BeanPostProcessor after initialization.
Bean ready for use.
Destruction (@PreDestroy or destroy() method).
@ComponentScan and context:component-scan?Answer:
@ComponentScan – Annotation-based configuration for scanning beans.
<context:component-scan> – XML-based configuration.
Answer:
SpEL is a powerful expression language for querying and manipulating objects at runtime.
Example:
@Value("#{2 * 3}")
private int value; // value = 6
Answer:
Spring provides @ExceptionHandler in controllers for custom handling.
ControllerAdvice can handle exceptions globally.
Spring also wraps database exceptions into DataAccessException.
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.
@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
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.
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.
@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.
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)
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 |
@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.
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);
}
@RestController and @ControllerAnswer:
| 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.
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.
@ControllerAdvice and @ExceptionHandlerAnswer:
@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);
}
}
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
BeanFactory and ApplicationContext in real-timeAnswer:
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.
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.
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 |
@RequestBody and @ResponseBodyAnswer:
@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; }
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.
@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.
@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.
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.
| 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 |
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.
@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.
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);
Answer:
WebClient is the reactive replacement for RestTemplate.
Supports async requests.
Part of 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 |
Answer:
Unit testing: Using @MockBean and Mockito
Integration testing: Using @SpringBootTest
Web layer testing: Using @WebMvcTest
Scenario:
@SpringBootTest
class UserServiceTest {
@Autowired
private UserService userService;
}
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.
Answer:
Spring Cache allows automatic caching of method results to improve performance.
Example:
@Cacheable("users")
public User getUser(Long id) { ... }
Answer:
Layers: Controller, Service, Repository
Transactions: Use @Transactional for money transfers
Security: Spring Security with roles (Admin, User)
Logging: Spring AOP for auditing
REST APIs: Use @RestController and DTOs
Database: Spring Data JPA
Caching: Spring Cache for frequently accessed accounts
Monitoring: Spring Boot Actuator
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.
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.
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.
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.
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.
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.
Answer:
Options:
Declarative: @Transactional
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.
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.
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.
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.
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.
@Component, @Service, @Repository in enterprise appsAnswer:
@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.
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.
Answer:
Use Flyway or Liquibase.
Auto-executed on startup to maintain versioned DB schema.
Scenario: Avoids inconsistencies when deploying to multiple environments.
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.
Answer:
Use Spring Batch for large-scale jobs.
Supports chunk-based processing, retry mechanisms, and scheduling.
Scenario: Processing millions of transactions overnight.
| 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 |
Answer:
Spring JMS: For ActiveMQ or RabbitMQ.
Spring Kafka: For Kafka topics.
Scenario: Microservices communicating asynchronously for order processing.
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.
Answer:
Spring Boot Actuator: Health, metrics, environment.
Micrometer: Integrates with Prometheus/Grafana.
Scenario: Monitor memory, CPU, DB connections in real-time.
Answer:
Use Spring WebFlux with Mono and Flux.
Supports non-blocking I/O for high concurrency applications.
Example:
@GetMapping("/users")
public Flux<User> getAllUsers() { ... }
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.
Answer:
Solution: Use @Lazy or constructor injection refactoring.
Avoid field injection when possible.
Answer:
@Conditional, @Profile, or @ConditionalOnProperty
Scenario: Create bean only in dev environment or if a property exists.
Answer:
Use ResourceBundleMessageSource and LocaleResolver.
Scenario: Multi-country applications with language-specific messages.
| Feature | RestTemplate (Blocking) | WebClient (Non-blocking) |
|---|---|---|
| Blocking | Yes | No |
| Reactive | No | Yes |
| Performance | Lower under load | Higher under high concurrency |
Answer:
URL versioning: /api/v1/users
Header versioning: X-API-VERSION: 1
Scenario: Maintain backward compatibility with clients.
Answer:
Use MultipartFile with @RequestParam.
Scenario: Large files handled asynchronously or stored in cloud storage.
Answer:
Use @ConfigurationProperties or @Value.
Scenario: Externalized configuration for microservices.
Answer:
Use @EnableScheduling and @Scheduled(cron = "...").
Scenario: Data cleanup, report generation, periodic polling.
Answer:
Redis, EhCache, Caffeine
Use @Cacheable and @CacheEvict annotations
Scenario: Frequently accessed data like product catalog.
Answer:
Strategies: STATELESS (JWT), STATEFUL (HTTP session)
Prevent session fixation, concurrent logins, timeout.
Answer:
@PreAuthorize("hasRole('ADMIN')")
Scenario: Different roles (Admin/User/Manager) for API endpoints.
Answer:
Use spring-security-oauth2-client
Supports Google/Facebook login
Scenario: Single Sign-On in enterprise portals.
Answer:
Use Spring Boot Filter/Interceptor or Bucket4j
Scenario: Prevent abuse of public REST APIs.
Answer:
Schema-based, Database-based, or Discriminator-based
Scenario: SaaS applications serving multiple clients in a single DB.
Answer:
Use caching, lazy loading, connection pooling, pagination, async processing
Monitor with Actuator + Micrometer
Scenario: Reduce DB hits in high traffic services.
Answer:
Use Spring Boot + JTA/XA Transactions or Saga Pattern
Scenario: Order service updates inventory, payment, and shipping across microservices.
Answer:
Use @EnableAsync and @Async
Scenario: Send emails without blocking user requests.
Answer:
Producer/Consumer with @RabbitListener or @KafkaListener
Scenario: Event-driven architecture for microservices.
Answer:
Unit testing: Mockito, @MockBean
Integration testing: @SpringBootTest
Web layer: @WebMvcTest
Scenario: Testing REST endpoints without hitting production DB.
Answer:
spring.lifecycle.timeout-per-shutdown-phase
Scenario: Finish ongoing requests before shutdown.
Answer:
Prefer constructor injection
Use @Lazy annotation to break circular reference
Answer:
Use JWT filters, OAuth2, role-based access
Scenario: API Gateway handles authentication for multiple services.
Answer:
Use Spring Data R2DBC or MongoDB reactive repositories
Scenario: High throughput non-blocking database calls.
Answer:
Use @ControllerAdvice across services
Scenario: Consistent error responses across APIs.
Answer:
Use Spring Cloud Config Server with Git
Scenario: Centralized property management.
Answer:
Use Eureka server
Scenario: Dynamically discover instances in microservices architecture.
Answer:
Use Resilience4j or Hystrix
Scenario: Prevent cascading failures in dependent services.
Answer:
Use Spring Cloud Sleuth + Zipkin
Scenario: Track requests across microservices for debugging and monitoring.
Answer:
Use Springfox Swagger or Springdoc OpenAPI
Scenario: REST APIs easily discoverable and testable.
Answer:
Use Spring Cloud Config + Spring Cloud Bus
Scenario: Update properties without restarting microservices.
Answer:
Spring Boot Actuator /actuator/health
Scenario: Monitor DB, messaging, disk space, and dependencies.
Answer:
Use Fallback methods with Resilience4j
Scenario: Service fails → fallback response ensures UX continuity.
Answer:
Layers: Controller, Service, Repository
Transaction management: @Transactional
Security: OAuth2 + JWT + Role-based access
Caching: Redis for frequent queries
Async processing: Email notifications, SMS alerts
Event-driven: Kafka for audit logs
Monitoring: Actuator + Prometheus
Testing: Unit and integration testing with mocks and embedded DB