Skip to content

Instantly share code, notes, and snippets.

@srirajk
Created June 26, 2024 16:52
Show Gist options
  • Save srirajk/818e53f4c93c5de7fce52e6349ecc69a to your computer and use it in GitHub Desktop.
Save srirajk/818e53f4c93c5de7fce52e6349ecc69a to your computer and use it in GitHub Desktop.

Spring Context and Beans

  1. What is the purpose of the ApplicationContext in Spring?

    • Answer: The ApplicationContext in Spring is the central interface for providing configuration information to the application. It is a step above simple bean factories because it can handle Spring AOP integrations, transaction management, and provides a means to read configuration metadata from various sources such as XML, annotations, or Java configurations.
  2. How do you define bean scopes in Spring, and what are their implications?

    • Answer: In Spring, bean scopes define the lifecycle and visibility of a bean in the container. The scopes are:
      • Singleton: (Default) Restricts the bean instance to one per Spring IoC container.
      • Prototype: Creates a new bean instance each time it is requested.
      • Request: Creates a bean instance per HTTP request. (valid only in a web-aware Spring ApplicationContext)
      • Session: Creates a bean instance per HTTP session. (valid only in a web-aware Spring ApplicationContext)
      • GlobalSession: Creates a bean instance per global HTTP session. (primarily used in a Portlet context)
      • Application: Scopes a single bean definition to the lifecycle of a ServletContext. Available only if you use a web-aware Spring ApplicationContext.
    • The choice of scope impacts how an application configures and manages dependencies.
  3. What is the role of the BeanFactoryPostProcessor and how is it different from BeanPostProcessor?

    • Answer: BeanFactoryPostProcessor modifies the application's bean definitions before the Spring container instantiates any beans. Its primary purpose is to interact with and modify bean definitions in the configuration metadata.
      • BeanPostProcessor, on the other hand, operates on bean instances, i.e., it processes beans after the container instantiates them but before Spring initializes them. It can be used to implement custom logic before or after the Spring initialization process of a bean.
  4. Explain the concept of dependency injection in Spring. What are the different types of dependency injection supported by Spring?

    • Answer: Dependency injection (DI) is a core component of the Spring Framework, used to achieve Inversion of Control (IoC) between components. The two primary types of DI in Spring are:
      • Constructor Injection: Dependencies are provided through class constructors.
      • Setter Injection: Dependencies are injected through JavaBean-style setter methods.
    • Spring also supports method injection where dependencies are provided through other methods in the beans.
  5. How can PropertySourcesPlaceholderConfigurer be used in Spring?

    • Answer: PropertySourcesPlaceholderConfigurer is used in Spring to externalize configuration to properties files and resolve ${...} placeholders within bean definition property values and @Value annotations against the current Spring Environment and its set of PropertySources.
  6. Describe the process of event handling in Spring.

    • Answer: Spring’s event handling is an application of the Observer pattern. You can create and publish events that various beans can listen to:
      • Custom Events: Extend ApplicationEvent and publish them using ApplicationEventPublisher.
      • Event Listener: Annotate methods with @EventListener to handle events. These methods can listen to standard Spring events (like ContextRefreshedEvent) or custom events.
      • Events are synchronously handled by default, but can be made asynchronous with @Async annotation on the event listener.
  7. What is a Spring bean and how are beans configured and managed within the Spring container?

    • Answer: A Spring bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. These beans are created with the configuration metadata that you supply to the container, which can be XML, annotations, or Java config. Beans can be configured with scope, lifecycle callbacks, and dependencies that the container injects.

Spring Boot and REST API Questions

  1. What are the benefits of using Spring Boot for developing REST APIs?

    • Answer: Spring Boot provides a range of benefits for REST API development:
      • Auto-configuration: Automatically configures your application based on the dependencies you have added. This simplifies the setup and configuration of applications.
      • Standalone: Allows applications to be run independently without the need for an external web server.
      • Opinionated Defaults: Offers a range of 'starter' POMs to simplify Maven configurations.
      • Embedded Servers: Makes it easy to develop web applications that can be started with embedded servers like Tomcat or Jetty.
      • Management Endpoints: Provides ready-to-use features for monitoring and managing the application in production.
  2. How do you handle exception handling in Spring Boot REST APIs?

    • Answer: Exception handling in Spring Boot REST APIs can be centralized using @ControllerAdvice and @ExceptionHandler annotations. This approach allows you to define a global exception handler for your application:
    @ControllerAdvice
    public class GlobalExceptionHandler {
        @ExceptionHandler(value = Exception.class)
        public ResponseEntity<Object> handleException(Exception e) {
            return new ResponseEntity<>("An error occurred: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    • This method captures exceptions thrown by any controller and returns a more user-friendly error response.
  3. Discuss how you can secure a REST API in Spring Boot.

    • Answer: Securing a REST API in Spring Boot can typically be done using Spring Security. Steps include:
      • Dependency Addition: Add Spring Security to your project.
      • Configuration: Configure security settings via Java configuration to specify endpoints that need security, authentication mechanisms, etc.
      • Implement Authentication and Authorization: Define how users are authenticated (e.g., JWT, OAuth) and how requests are authorized.
      • Secure Endpoints: Use annotations such as @PreAuthorize to secure individual controllers or endpoints based on user roles.
  4. Explain how you would implement versioning in a Spring Boot REST API.

    • Answer: Versioning can be implemented in several ways:
      • URI Versioning: Include the API version in the URI path (e.g., /api/v1/products).
      • Parameter Versioning: Use a request parameter to control the version (e.g., /api/products?version=1).
      • Header Versioning: Use custom request headers to specify the version.
      • Media type versioning: Version is indicated in the Accept header field as part of the content type (e.g., application/vnd.company.app-v1+json).
    • Each method has its trade-offs, and the choice can depend on factors like API consumer preferences and the nature of the changes.
  5. How can you document a REST API developed with Spring Boot?

    • Answer: REST API documentation in Spring Boot can efficiently be handled using tools like Swagger (OpenAPI). Spring Boot supports Swagger integration through libraries like Springfox or Springdoc-openapi. These tools automatically generate and serve interactive API documentation, which can be customized using annotations in your controller classes.
  6. Describe how Spring Boot supports data pagination in a REST API.

    • Answer: Spring Boot can leverage Spring Data to support pagination easily. By extending PagingAndSortingRepository or using Pageable in controller methods, developers can add pagination support:
    @GetMapping("/users")
    public ResponseEntity<Page<User>> getAllUsers(Pageable pageable) {
        Page<User> page = userRepository.findAll(pageable);
        return new ResponseEntity<>(page, HttpStatus.OK);
    }
    • This method automatically applies pagination and sorting based on the query parameters provided by the client, such as page, size, and sort.

Great! Let's move on to Spring Batch, exploring in-depth questions that evaluate a candidate's understanding and practical skills in batch processing with Spring.

Spring Batch Questions

  1. What is Spring Batch, and what are its typical use cases?

    • Answer: Spring Batch is a framework for writing robust batch applications used for processing large volumes of data typically within business processes. It is designed to be highly scalable and extensible. Typical use cases include financial transactions processing, bulk data import/export, and complex computational tasks that need to be performed on a scheduled basis.
  2. Explain the architecture of Spring Batch and the role of its major components.

    • Answer: Spring Batch follows a layered architecture that includes:
      • Job: A batch process that encapsulates an entire batch run.
      • Step: A domain within a Job, representing a single task that involves reading data, processing it, and writing it to a database or other system.
      • ItemReader, ItemProcessor, ItemWriter: Components that read data from a resource, process it (optional), and write it elsewhere, respectively.
      • JobRepository: Stores metadata about the execution of a job.
      • JobLauncher: Used to launch jobs with various configurations.
      • This architecture allows developers to focus on business logic while the framework handles the infrastructure.
  3. How does Spring Batch handle transaction management?

    • Answer: Spring Batch provides a robust transaction management that is integrated into the read-process-write cycle. It typically manages transactions at the step level, where each chunk of items is processed in a transaction. Customization is possible to span transactions over multiple chunks if required, using appropriate transaction attributes and isolation levels.
  4. Can you describe how to scale and optimize performance in Spring Batch jobs?

    • Answer: Scaling and optimizing performance in Spring Batch can be achieved through:
      • Multi-threading: Configure a step to run with multiple threads to process chunks in parallel.
      • Parallel Processing: Use Partitioner to split the data into multiple partitions that can be processed in parallel.
      • Asynchronous Processing: Utilize asynchronous item processors and writers to improve throughput.
      • Optimal Resource Usage: Tune the chunk size and optimize reader and writer to handle larger data sets efficiently.
  5. What is a JobLauncher and how is it used in Spring Batch?

    • Answer: A JobLauncher is a component in Spring Batch that is used to launch batch jobs. It provides a simple interface with methods to start or resume jobs. A JobLauncher can be used programmatically or configured via Spring's task scheduling support to run jobs at specific intervals or times.
  6. Explain chunk-oriented processing in Spring Batch.

    • Answer: Chunk-oriented processing involves reading data one at a time, and buffering it until a chunk (a collection of items) is complete. Once the chunk is complete, the entire chunk is processed and then written out in one transaction. This approach is efficient because it balances the overhead of context switching and transaction management with the efficiency of batch processing.
  7. Describe how you would implement error handling in a Spring Batch job.

    • Answer: Error handling in Spring Batch can be managed through:
      • Skip Logic: Configure a step to skip certain exceptions and continue processing.
      • Retry Logic: Define retryable exceptions and the retry limit.
      • Listeners: Implement step or chunk listeners to handle errors or perform specific actions when job execution changes states (e.g., on error, before/after step).
      • Failures: Use job and step executions to decide when a job or step may need to be rerun or marked as failed.
  8. How do you restart a Spring Batch job that has failed?

    • Answer: Spring Batch jobs can be restarted using JobRepository. When a job fails, metadata about its execution, including where it failed, is stored. A job configured as restartable can be launched again using the same JobParameters, and it will continue from the point of failure, assuming the job's steps are idempotent.

Let's continue with detailed questions for Spring Data, focusing on how it simplifies the data handling in Spring applications.

Spring Data Questions

  1. What is Spring Data, and what are its core features?

    • Answer: Spring Data is a part of the larger Spring ecosystem that makes it easier to work with data access technologies. Its core features include:
      • Repository abstraction: Simplifies CRUD operations with no boilerplate code.
      • Consistent data access APIs: Provides a consistent programming model across different data stores.
      • Query derivation from method names: Automatically creates queries from repository method names.
      • Annotation-based configuration: Reduces the amount of manual configuration and setup.
  2. How do you define a repository interface in Spring Data?

    • Answer: In Spring Data, a repository interface is defined by extending one of the several sub-interfaces of Repository, such as CrudRepository or PagingAndSortingRepository. For example:
    public interface UserRepository extends CrudRepository<User, Long> {
        List<User> findByLastName(String lastName);
    }
    • This interface automatically provides CRUD operations on User entities and allows for the creation of additional queries based on method names.
  3. Explain how custom queries can be defined in Spring Data repositories.

    • Answer: Custom queries in Spring Data repositories can be defined using the @Query annotation. This can include JPQL (Java Persistence Query Language) or native SQL queries. For example:
    public interface UserRepository extends JpaRepository<User, Long> {
        @Query("SELECT u FROM User u WHERE u.email = ?1")
        User findByEmailAddress(String emailAddress);
    }
    • This method allows for more complex queries than those derived from method names.
  4. Discuss the strategies for implementing paging and sorting in Spring Data.

    • Answer: Paging and sorting in Spring Data can be implemented by extending PagingAndSortingRepository or using the Pageable and Sort parameters in repository methods. For example:
    Page<User> findByLastName(String lastName, Pageable pageable);
    • This method will return a Page<User> object that includes the data in a paginated format, which can be controlled by passing a Pageable object when calling the method.
  5. What are projections in Spring Data, and how are they useful?

    • Answer: Projections in Spring Data allow you to define interfaces or DTOs (Data Transfer Objects) that capture only a subset of the attributes of a domain model. This is useful for optimizing performance and reducing network traffic by fetching only the necessary data. For example:
    interface UserNameProjection {
        String getFirstName();
        String getLastName();
    }
    
    List<UserNameProjection> findByLastName(String lastName);
    • This query would only fetch the firstName and lastName fields of User entities.
  6. How does Spring Data integrate with the Spring transaction management?

    • Answer: Spring Data integrates seamlessly with Spring's transaction management. By default, repository methods are transactional and can be customized using the @Transactional annotation. This ensures that methods involving multiple database operations are treated as a single transactional unit, thus maintaining data integrity.
  7. What is the role of @EnableJpaRepositories in Spring Data?

    • Answer: The @EnableJpaRepositories annotation enables the auto-configuration of JPA repositories in a Spring application. It scans the specified packages for interfaces extending Repository and configures them as JPA repositories, suitable for injection into other components.
  8. Describe how optimistic locking is supported in Spring Data.

    • Answer: Optimistic locking in Spring Data can be implemented using the @Version annotation. This approach involves adding a version field to the domain model, which Spring Data automatically increments on each update, ensuring that conflicts are detected when concurrent updates occur.
    @Entity
    public class User {
        @Id
        private Long id;
        private String name;
    
        @Version
        private Long version;
    }
    • When an update is attempted with an outdated version number, an OptimisticLockingFailureException is thrown, preventing the update.

Spring Security Questions

  1. What is Spring Security, and what are its core features?

    • Answer: Spring Security is a powerful and highly customizable authentication and access-control framework. Its core features include:
      • Comprehensive and extensible support for authentication and authorization.
      • Protection against attacks like session fixation, clickjacking, cross-site request forgery, etc.
      • Integration with various authentication providers, including LDAP, JDBC, OAuth2, and OpenID Connect.
      • Method level security with annotations.
      • Optional integration with Spring MVC.
  2. Explain the role of FilterChain in Spring Security.

    • Answer: The FilterChain is a fundamental component in Spring Security, representing a series of filters that are applied to incoming requests to perform various security checks and tasks before reaching the application. Each filter has a specific responsibility, such as authentication, logging out, checking for CSRF tokens, etc. This chain is highly configurable, allowing developers to add or remove filters as needed for their security requirements.
  3. How does Spring Security handle user authentication and authorization?

    • Answer: Spring Security handles user authentication by using an AuthenticationManager, which delegates to one or more AuthenticationProvider instances. Each provider can support different authentication types (like username/password, tokens, etc.). After authentication, an Authentication object is created and stored in the SecurityContextHolder.
      • Authorization is then performed using this authentication information to determine whether the user has the required permissions or roles to access specific resources or execute operations.
  4. Discuss the configuration steps for integrating OAuth2 in a Spring Boot application for securing REST APIs.

    • Answer: To configure OAuth2 with Spring Boot for securing REST APIs, you typically need to:
      • Add dependencies: Include spring-security-oauth2-client and spring-security-oauth2-jose.
      • Configure properties: Define client registration and provider details in application.yml or application.properties.
      • Enable OAuth2: Use @EnableOAuth2Client or similar annotations depending on the exact approach (e.g., client, resource server).
      • Define security configuration: Extend WebSecurityConfigurerAdapter and define how the OAuth tokens are obtained, checked, and what resources are protected.
      • Implement token services: Set up services to issue, store, and validate tokens.
  5. What is OpenID Connect and how does it differ from OAuth2?

    • Answer: OpenID Connect is an identity layer on top of the OAuth2 protocol that allows clients to verify the identity of an end-user based on authentication performed by an authorization server. It also obtains basic profile information about the end-user in an interoperable and REST-like manner.
      • While OAuth2 provides delegated authorization to access resources, OpenID Connect uses OAuth2 authentication mechanisms to provide identity verification. Essentially, OAuth2 allows you to obtain tokens, whereas OpenID Connect allows you to obtain tokens along with identity information.
  6. How do you secure a method using Spring Security?

    • Answer: Methods can be secured using Spring Security by applying the @PreAuthorize, @PostAuthorize, @Secured, or @RolesAllowed annotations. For example:
    @PreAuthorize("hasRole('ADMIN')")
    public void performAdminFunction() {
        // code here
    }
    • These annotations ensure that method invocations are allowed only if the authentication in the SecurityContext meets the specified conditions.
  7. Describe how you can use JWT with Spring Security for securing a REST API.

    • Answer: Using JWT (JSON Web Tokens) with Spring Security involves:
      • Implementing an authentication filter: Create a custom filter to parse and verify JWTs from request headers.
      • Configuring HttpSecurity: Customize the security configuration to use the JWT filter, specifying routes that require authentication.
      • Handling token generation and response: After a successful login, generate a JWT and send it back to the user, which will be used in subsequent requests.
      • Validating tokens: Each request with a JWT is validated for integrity and expiry.
  8. Explain the difference between @PreAuthorize and @Secured annotations in Spring Security.

    • Answer: Both annotations are used to enforce security policies on methods:
      • @PreAuthorize: Allows for complex expressions, such as @PreAuthorize("hasRole('ROLE_ADMIN') and hasPermission('WRITE')"). It evaluates the expression before entering the method.
      • @Secured: Simpler but less flexible, as it only supports role-based constraints,
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment