Spring Boot Java Interview Guide
Spring Boot Java Interview Guide
Transaction propagation determines the behavioral relationship between a transactional method and any transactional context that is currently active. Each propagation type affects transactionality and consistency. 'REQUIRED' will participate in an existing transaction or create a new one if none exists, ensuring consistency as one transaction context is maintained. 'REQUIRES_NEW' always creates a new transaction, suspending any existing transaction; this is useful for operations that should commit or rollback independently. 'MANDATORY' requires an existing transaction, throwing an exception if none is active, enforcing consistency. Each propagation type is specific to transaction management needs, affecting how state consistency is maintained across transactional boundaries.
Spring Security utilizes JWTs (JSON Web Tokens) to secure REST APIs by means of token-based authentication. When a user logs in, a JWT is generated and sent to the client. The client must include this token in the Authorization header of future requests. The server can then use this token to authenticate the user without needing to interact with the storage layer each time. The benefits include statelessness, as session data does not need to be stored on the server, as well as scalability, ease of integration with single-page applications, and compatibility with mobile applications. This method also allows easy implementation of stateless session management and scales well to distributed systems.
@RequestBody is used to map the request body to a method parameter. This is typically used when the data is in JSON or XML format and you want it to be automatically converted into a corresponding Java object. On the other hand, @RequestParam is used to extract query parameters, form data, or fragments from a URL. It is typically used for parameters that are appended to the URL and does not involve complex data mapping.
The @SpringBootApplication annotation simplifies application configuration by being a composite of three annotations: @Configuration, @EnableAutoConfiguration, and @ComponentScan. @Configuration indicates that the class can be used by the Spring IoC container as a source of bean definitions. @EnableAutoConfiguration attempts to automatically configure your Spring application based on the dependencies that you have added. Finally, @ComponentScan enables automatic detection of beans by scanning the package where the application is located and its sub-packages. This single annotation thus greatly reduces the need for explicit configuration.
An API Gateway acts as a single entry point to a microservices-based system. It contributes to security by handling authentication, access control, and routing requests to the appropriate services. By centralizing these operations, an API Gateway ensures that security policies are uniformly enforced across all services. In terms of efficiency, the API Gateway can perform load balancing, caching, and request transformation, thus reducing the overhead on individual services. It also helps in minimizing the client-side complexity by aggregating multiple services into a single call to deliver composite data, which reduces the number of requests made from the client.
To make a Spring Boot application production-ready, it is important to implement several key practices. Profiles allow for separating configuration for different environments like development, testing, and production, facilitating better configuration management. Robust logging is essential for diagnosing issues in production, and monitoring enables proactive alerting for anomalies and performance degradation. Externalized configurations make it easy to change settings without needing to rebuild or redeploy applications. Comprehensive exception handling ensures that errors are captured and managed gracefully, providing a better user experience. These practices ensure better performance, reliability, scalability, and maintainability of applications, offering a seamless transition to production environments.
Eager fetching in JPA can lead to performance issues because it loads all related entities immediately at the time of fetching the owning entity. This can be resource-intensive and result in loading more data than necessary, impacting application performance, especially if many entities are interrelated. The N+1 problem arises when instead of retrieving all related entities in a single join query, separate queries are executed for each related entity, leading to a total of N+1 queries. Using Eager fetching exacerbates this issue as SQL queries are executed multiple times unnecessarily, which can be resolved using JOIN FETCH or EntityGraph to optimize data retrieval.
ConcurrentHashMap addresses thread safety by using a segmented locking mechanism, which allows concurrent reads and updates to different segments of the map. This reduces the contention by locking only a portion of the map and allows for higher throughput during concurrent operations. On the other hand, HashMap is not thread-safe and can lead to data inconsistency if accessed concurrently by multiple threads. In a multi-threaded environment, without external synchronization, HashMap might result in a corrupted state or an infinite loop.
To debug a slow API in a Spring Boot application, several strategies can be employed: reviewing logs helps identify error messages or time-stamped anomalies; analyzing database queries and ensuring indexes are properly used can reduce time-consuming DB operations; implementing caching reduces redundant data processing; checking thread pool configurations ensures sufficient resources for handling requests; and using Spring Boot's Actuator metrics provides insights into application health, such as memory usage and request handling times. These approaches help identify the specific areas causing delays, allowing targeted optimization of processing, data handling, and resource allocation.
CrudRepository provides basic CRUD operations like save, findAll, findById, and delete. It serves as a base interface primarily for generic CRUD operations on a repository for a specific type. JpaRepository extends CrudRepository and adds more JPA-specific methods such as flushing the persistence context and deleting records in a batch. It also provides pagination and sorting out of the box. This extended interface is useful for applications that need more than basic CRUD and enables the manipulation of more complex JPA entities.