Top Spring Framework Interview Questions

    1

    What is the Spring Framework?

    The Spring Framework is a powerful and comprehensive application framework for Java. It provides a wide range of features to build robust, scalable, and maintainable enterprise-level applications. At its core, Spring is built on the principles of Inversion of Control (IoC) and Dependency Injection (DI), which help in creating loosely coupled applications.

    Spring Framework Ecosystem Core Container Beans, Core, Context, SpEL (IoC & Dependency Injection) Data Access JDBC, ORM, OXM, JMS Web Web, Servlet, REST AOP & Aspects AOP, Aspects, Instrumentation Test Mock Objects, TestContext Security Spring Security, OAuth2 Batch Spring Batch Integration Spring Integration Cloud Spring Cloud, Config AI Spring AI

    Key Features:

    • Inversion of Control (IoC): The framework manages the lifecycle and configuration of application objects (beans).
    • Dependency Injection (DI): Objects define their dependencies, and the Spring container injects them.
    • Aspect-Oriented Programming (AOP): Enables modularization of cross-cutting concerns like logging, security, and transactions.
    • Data Access: Simplifies database interaction with support for JDBC, ORM (like Hibernate), and transaction management.
    • Web MVC: A robust framework for building web applications.
    • Testing: Provides excellent support for unit and integration testing.

    Why use Spring?

    • Loose Coupling: DI makes components independent of each other.
    • Modularity: AOP helps in separating concerns.
    • Reduced Boilerplate: Templates for JDBC, REST, etc., simplify code.
    • Flexibility: Can be used for various types of applications, from small standalone utilities to large enterprise systems.
    • Strong Ecosystem: Projects like Spring Boot, Spring Data, and Spring Security provide comprehensive solutions for common problems.
    2

    What is Dependency Injection (DI) and Inversion of Control (IoC)?

    Inversion of Control (IoC) is a design principle where the control of object creation and lifecycle is transferred from the application to a container or framework. In traditional programming, the developer creates objects and manages their dependencies. With IoC, the framework takes over this responsibility.

    Dependency Injection (DI) is a design pattern that implements IoC. It's the process whereby the Spring container "injects" the dependencies (i.e., other objects) that a bean needs.

    Traditional Approach OrderService OrderRepository creates IoC / Dependency Injection Spring IoC Container OrderService OrderRepository injects

    Types of Dependency Injection:

    1. Constructor Injection: Dependencies are provided through the class constructor. This is the recommended approach as it ensures that an object is created with all its required dependencies.

      @Service public class OrderService { private final OrderRepository orderRepository; @Autowired public OrderService(OrderRepository orderRepository) { this.orderRepository = orderRepository; } }
    2. Setter Injection: Dependencies are injected through setter methods. This is useful for optional dependencies.

      @Service public class OrderService { private OrderRepository orderRepository; @Autowired public void setOrderRepository(OrderRepository orderRepository) { this.orderRepository = orderRepository; } }
    3. Field Injection: Dependencies are injected directly into the fields using the @Autowired annotation. While simple, this approach is generally discouraged because it makes testing more difficult and can hide dependencies.

      @Service public class OrderService { @Autowired private OrderRepository orderRepository; }
    3

    What is a Spring Bean? What is its lifecycle?

    A Spring Bean is an object that is instantiated, assembled, and otherwise managed by the Spring IoC container. Beans are the fundamental building blocks of any Spring application.

    Bean Lifecycle: The lifecycle of a bean is the sequence of events from its instantiation to its destruction.

    Spring Bean Lifecycle 1. Instantiation Container creates bean instance 2. Populate Properties Inject dependencies (DI) 3. Initialization @PostConstruct, afterPropertiesSet() Bean is Ready Bean is in use 4. Destruction @PreDestroy, destroy()

    Lifecycle Callbacks:

    • @PostConstruct: A method annotated with @PostConstruct is executed after the bean has been constructed and its dependencies have been injected.
    • @PreDestroy: A method annotated with @PreDestroy is called just before the bean is removed from the container.

    Example:

    @Component public class MyBean { public MyBean() { System.out.println("1. Constructor called"); } @Autowired public void setDependency(MyDependency dependency) { System.out.println("2. Setter for dependency called"); } @PostConstruct public void init() { System.out.println("3. @PostConstruct: Bean is initialized"); } public void doWork() { System.out.println("Bean is doing work..."); } @PreDestroy public void cleanup() { System.out.println("4. @PreDestroy: Bean is about to be destroyed"); } }
    4

    What are the different bean scopes in Spring?

    Bean scope determines the lifecycle and visibility of a bean in a specific context. Spring supports several scopes:

    • singleton: (Default) Only one instance of the bean is created for the entire Spring container.
    • prototype: A new instance of the bean is created every time it is requested.
    • request: A new instance is created for each HTTP request. (Web-aware ApplicationContext only)
    • session: A new instance is created for each HTTP session. (Web-aware ApplicationContext only)
    • application: A single instance is created for the lifecycle of a ServletContext. (Web-aware ApplicationContext only)
    • websocket: A single instance is created for the lifecycle of a WebSocket session. (Web-aware ApplicationContext only)
    Spring Bean Scopes Singleton One instance per container Prototype New instance per request Request One instance per HTTP request Session One instance per HTTP session Application One instance per ServletContext

    Example of setting scope:

    import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; @Component @Scope("prototype") public class MyPrototypeBean { public MyPrototypeBean() { System.out.println("MyPrototypeBean instance created: " + this); } } @Component @Scope("singleton") // This is the default, so it's optional public class MySingletonBean { public MySingletonBean() { System.out.println("MySingletonBean instance created: " + this); } }
    5

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

    These are stereotype annotations that mark a class as a Spring bean. While @Component is a generic stereotype, @Service, @Repository, and @Controller are specializations of @Component for more specific use cases.

    • @Component: A generic annotation for any Spring-managed component. It's the base for all other stereotype annotations.
    • @Service: Indicates that a class is a service, typically used in the business logic layer.
    • @Repository: Indicates that a class is a repository, responsible for data access. It also enables exception translation for data access exceptions.
    • @Controller: Indicates that a class is a controller in a Spring MVC application, responsible for handling web requests.
    @Component @Service @Repository @Controller

    Example:

    // Generic component @Component public class MyComponent { // ... } // Service layer @Service public class UserServiceImpl implements UserService { @Autowired private UserRepository userRepository; // Business logic } // Data access layer @Repository public interface UserRepository extends JpaRepository<User, Long> { // Exception translation is automatically enabled } // Web layer @Controller public class UserController { @Autowired private UserService userService; // Request handling methods }
    6

    What is Spring Boot and how is it different from Spring?

    Spring Boot is an extension of the Spring framework that simplifies the development of stand-alone, production-grade Spring-based applications. It takes an "opinionated" view of the Spring platform, which means it makes assumptions about how to configure the application and what dependencies to use.

    Key Differences:

    FeatureSpringSpring Boot
    ConfigurationManual configuration (XML or Java-based)Automatic configuration (auto-configuration)
    SetupRequires significant setup and boilerplateMinimal setup, "just run" applications
    DependenciesManual dependency managementSimplified with "starters"
    ServerRequires external server (e.g., Tomcat)Embedded server (Tomcat, Jetty, Undertow)
    GoalTo provide a flexible and powerful frameworkTo simplify the development of Spring apps
    Spring Framework Manual XML/Java Config Manual Dependency Management External Server Required Spring Boot Auto-Configuration Starter Dependencies Embedded Server

    Key Features of Spring Boot:

    • Auto-configuration: Automatically configures the application based on the dependencies present on the classpath.
    • Starter dependencies: A set of convenient dependency descriptors that you can include in your application. For example, spring-boot-starter-web includes all the necessary dependencies for building a web application.
    • Embedded server: Comes with embedded Tomcat, Jetty, or Undertow servers, so you can run your application as a standalone JAR.
    • Actuator: Provides production-ready features like health checks, metrics, and monitoring.
    7

    What is Spring AOP? Explain some common AOP concepts.

    Aspect-Oriented Programming (AOP) is a programming paradigm that aims to increase modularity by allowing the separation of cross-cutting concerns. AOP breaks down program logic into distinct parts called concerns. The core concern of the application is business logic, while cross-cutting concerns are functionalities that are used across multiple parts of the application, such as logging, security, and transaction management.

    Common AOP Concepts:

    • Aspect: A module that encapsulates a cross-cutting concern. In Spring, an aspect is a class annotated with @Aspect.
    • Join Point: A point during the execution of a program, such as the execution of a method or the handling of an exception.
    • Advice: Action taken by an aspect at a particular join point. Types of advice include @Before, @After, @Around, @AfterReturning, and @AfterThrowing.
    • Pointcut: A predicate that matches join points. Advice is associated with a pointcut expression and runs at any join point matched by the pointcut.
    • Target Object: The object being advised by one or more aspects.
    • Weaving: The process of linking aspects with other application types or objects to create an advised object. This can be done at compile time, load time, or runtime.
    Spring AOP Business Logic (Service Method) Logging Aspect Security Aspect Transaction Aspect Caching Aspect

    Example of an AOP logging aspect:

    @Aspect @Component public class LoggingAspect { private static final Logger logger = LoggerFactory.getLogger(LoggingAspect.class); @Pointcut("execution(* com.example.service.*.*(..))") public void serviceLayerExecution() {} @Before("serviceLayerExecution()") public void logBefore(JoinPoint joinPoint) { logger.info("Executing: " + joinPoint.getSignature().toShortString()); } @AfterReturning(pointcut = "serviceLayerExecution()", returning = "result") public void logAfterReturning(JoinPoint joinPoint, Object result) { logger.info("Finished executing: " + joinPoint.getSignature().toShortString()); logger.info("Returned: " + result); } }
    8

    How does Spring MVC work? Explain the role of the DispatcherServlet.

    Spring MVC (Model-View-Controller) is a web framework that provides a flexible and robust architecture for building web applications. At the heart of Spring MVC is the DispatcherServlet, which acts as the front controller. It receives all incoming requests and delegates them to the appropriate components for processing.

    The request processing workflow in Spring MVC is as follows:

    1. The client sends an HTTP request to the web server.
    2. The DispatcherServlet receives the request.
    3. The DispatcherServlet consults the HandlerMapping to determine which controller should handle the request.
    4. The DispatcherServlet calls the appropriate Controller.
    5. The Controller processes the request, performs business logic, and returns a ModelAndView object (or a view name).
    6. The DispatcherServlet uses a ViewResolver to resolve the logical view name into a physical View implementation.
    7. The View is rendered, and the response is sent back to the client.
    Spring MVC Request Flow (Simplified) Client DispatcherServlet Controller ViewResolver View Request Handler View Name View Response
    9

    What is the difference between @Controller and @RestController?

    Both @Controller and @RestController are used to define controllers in Spring MVC, but they have a key difference in how they handle responses.

    • @Controller: A traditional Spring MVC controller that returns a view. The return value of a method is typically a view name, which is then resolved by a ViewResolver to render a view (e.g., a JSP or Thymeleaf template). To return data directly (like JSON), you need to annotate the method with @ResponseBody.

    • @RestController: A specialized controller used for building RESTful web services. It's a combination of @Controller and @ResponseBody. With @RestController, every method's return value is automatically serialized into the response body (e.g., as JSON), so you don't need to add @ResponseBody to each method.

    For more details on Spring MVC, you can read more about it here.

    @Controller Example:

    @Controller public class MyViewController { @GetMapping("/hello") public String hello(Model model) { model.addAttribute("message", "Hello from @Controller!"); return "hello-view"; // Returns the view name } @GetMapping("/api/data") @ResponseBody // Required to return data public MyData getData() { return new MyData("some data"); } }

    @RestController Example:

    @RestController @RequestMapping("/api") public class MyRestController { @GetMapping("/hello") public MyData hello() { return new MyData("Hello from @RestController!"); // Automatically serialized to JSON } }
    10

    What is the `@Autowired` annotation? Explain the different types of autowiring.

    The @Autowired annotation is used for automatic dependency injection. It allows Spring to resolve and inject collaborating beans into your bean.

    Types of Autowiring:

    1. Constructor Injection: Spring injects dependencies through the constructor. This is the recommended approach.

      @Service public class MyService { private final MyRepository repository; @Autowired public MyService(MyRepository repository) { this.repository = repository; } }
    2. Setter Injection: Spring injects dependencies through setter methods.

      @Service public class MyService { private MyRepository repository; @Autowired public void setRepository(MyRepository repository) { this.repository = repository; } }
    3. Field Injection: Spring injects dependencies directly into the fields. This is generally discouraged due to testing difficulties.

      @Service public class MyService { @Autowired private MyRepository repository; }

    Autowiring by Type, Name, and Qualifier:

    • byType (Default): Spring looks for a bean of the same type as the property to be injected. If there's more than one bean of the same type, it will throw an exception.
    • byName: Spring looks for a bean with the same name as the property.
    • @Qualifier: When there are multiple beans of the same type, @Qualifier can be used to specify which bean to inject.
    • @Primary: Can be used on a bean to indicate that it should be the primary choice when multiple candidates are available for autowiring.

    Example with @Qualifier:

    public interface MessageService { String getMessage(); } @Component("emailService") public class EmailService implements MessageService { public String getMessage() { return "Email message"; } } @Component("smsService") public class SmsService implements MessageService { public String getMessage() { return "SMS message"; } } @Component public class MessageProcessor { private final MessageService messageService; @Autowired public MessageProcessor(@Qualifier("smsService") MessageService messageService) { this.messageService = messageService; } }
    11

    What is the difference between Authentication and Authorization?

    • Authentication is the process of verifying who a user is.
    • Authorization is the process of verifying what a user is allowed to do.

    For more details on JWT authentication in Spring 6, you can read more about it here.

    12

    What is a Filter in Spring Security?

    A Filter is a Java class that intercepts and processes HTTP requests before they reach the DispatcherServlet. Spring Security uses a chain of filters to apply security rules.

    13

    What is the DelegatingFilterProxy?

    DelegatingFilterProxy is a servlet filter that delegates to a Spring-managed bean that implements the Filter interface. This allows the filter to benefit from Spring's dependency injection and lifecycle management.

    14

    What is the `SecurityContextHolder`?

    The SecurityContextHolder is where Spring Security stores the details of the currently authenticated user.

    15

    What is the `@EnableWebSecurity` annotation?

    The @EnableWebSecurity annotation is used to enable Spring Security's web security support and provide the Spring MVC integration.

    16

    What is CORS and how do you handle it in Spring?

    CORS (Cross-Origin Resource Sharing) is a mechanism that allows resources to be requested from another domain. In Spring, you can handle CORS by using the @CrossOrigin annotation or by configuring it globally in your security configuration.

    17

    What is CSRF protection in Spring Security?

    CSRF (Cross-Site Request Forgery) is an attack that tricks the victim into submitting a malicious request. Spring Security provides CSRF protection by default.

    18

    What is method security and how do you enable it?

    Method security allows you to secure individual methods in your application. You can enable it by using the @EnableGlobalMethodSecurity annotation and then use annotations like @PreAuthorize and @PostAuthorize to secure your methods.

    19

    What is Spring Boot Actuator?

    Spring Boot Actuator is a sub-project of Spring Boot that provides production-ready features to help you monitor and manage your application. It exposes a set of endpoints that provide information about the application's health, metrics, configuration, and more.

    20

    What are some common Actuator endpoints?

    • /health: Shows application health information.
    • /metrics: Shows various metrics about the application.
    • /info: Displays arbitrary application info.
    • /beans: Displays a complete list of all Spring beans in your application.
    • /mappings: Displays a collated list of all @RequestMapping paths.
    • /configprops: Displays a collated list of all @ConfigurationProperties.
    • /env: Displays properties from Spring's ConfigurableEnvironment.
    • /threaddump: Performs a thread dump.
    • /heapdump: Returns a heap dump file.
    21

    How do you enable Actuator endpoints?

    To enable Actuator endpoints, you need to add the spring-boot-starter-actuator dependency to your project. By default, only the /health and /info endpoints are exposed over HTTP. You can expose other endpoints by setting the management.endpoints.web.exposure.include property in your application.properties file.

    management.endpoints.web.exposure.include=health,info,metrics,beans
    22

    What is Spring Boot DevTools?

    Spring Boot DevTools is a set of tools that can make the application development process easier. It provides features like automatic restart, live reload, and sensible development-time configuration.

    23

    What is application.properties (or application.yml) file?

    The application.properties (or application.yml) file is used to configure a Spring Boot application. It allows you to define properties for various aspects of the application, such as server port, database connection, logging, and more.

    24

    What is the difference between application.properties and bootstrap.properties?

    • application.properties: The main configuration file for a Spring Boot application.
    • bootstrap.properties: A special configuration file that is loaded before application.properties. It's used for configuration that needs to be available early in the application startup process, such as connecting to a configuration server.
    25

    What are Spring Profiles?

    Spring Profiles provide a way to segregate parts of your application configuration and make it only available in certain environments. You can use the @Profile annotation to mark beans or configuration classes that should only be loaded for a specific profile.

    26

    How do you activate a Spring Profile?

    You can activate a Spring Profile by setting the spring.profiles.active property in your application.properties file, or by passing it as a command-line argument.

    spring.profiles.active=dev
    27

    What is the `@ConfigurationProperties` annotation?

    The @ConfigurationProperties annotation is used to bind external configuration properties to a Java object. It provides a type-safe way to work with configuration properties.

    28

    What is the `@EnableAutoConfiguration` annotation?

    The @EnableAutoConfiguration annotation enables Spring Boot's auto-configuration mechanism. It attempts to automatically configure your Spring application based on the jar dependencies that you have added.

    29

    What is the `@Transactional` annotation?

    The @Transactional annotation is used to declare that a method or class should be executed within a database transaction. Spring provides a powerful transaction management framework that simplifies the handling of transactions in an application.

    30

    What are the different transaction propagation levels?

    Transaction propagation determines how transactions relate to each other. Spring defines the following propagation levels:

    • REQUIRED (Default): Supports a current transaction, creates a new one if none exists.
    • SUPPORTS: Supports a current transaction, executes non-transactionally if none exists.
    • MANDATORY: Supports a current transaction, throws an exception if none exists.
    • REQUIRES_NEW: Creates a new transaction, and suspends the current transaction if one exists.
    • NOT_SUPPORTED: Executes non-transactionally, suspends the current transaction if one exists.
    • NEVER: Executes non-transactionally, throws an exception if a transaction exists.
    • NESTED: Executes within a nested transaction if a current transaction exists, otherwise behaves like REQUIRED.
    31

    What is the difference between declarative and programmatic transaction management?

    • Declarative Transaction Management: You separate transaction management from the business code using annotations or XML configuration. This is the recommended approach in Spring.
    • Programmatic Transaction Management: You manage transactions explicitly in your code using the TransactionTemplate or the PlatformTransactionManager.
    Declarative @Transactional public void transferMoney(...){ // ... business logic } Programmatic transactionTemplate.execute(..);
    32

    What is the `JpaRepository` interface?

    JpaRepository is a Spring Data interface that provides sophisticated CRUD functionality for JPA-based data access layers. It extends the PagingAndSortingRepository and CrudRepository interfaces.

    33

    What is the difference between `CrudRepository` and `JpaRepository`?

    • CrudRepository: Provides basic CRUD operations.
    • PagingAndSortingRepository: Extends CrudRepository and adds methods for pagination and sorting.
    • JpaRepository: Extends PagingAndSortingRepository and adds JPA-specific methods like flush() and saveAndFlush().

    For more details on Spring JPA and data access, you can read more about it here.

    34

    How do you create custom repository methods in Spring Data?

    Spring Data can automatically create repository methods based on the method names. For example, a method named findByEmail(String email) will automatically generate a query to find a user by their email address.

    35

    What is the @Query annotation?

    The @Query annotation is used to provide a custom query for a repository method. This is useful when the method name is not sufficient to generate the desired query.

    36

    What is a projection in Spring Data?

    A projection allows you to selectively retrieve parts of an entity. You can create an interface that defines the properties you want to retrieve, and Spring Data will automatically implement it for you.

    37

    What is the Optional class and how is it used in Spring Data?

    Optional is a container object which may or may not contain a non-null value. Spring Data repositories use Optional to indicate that a query might not return a result. This helps to avoid NullPointerException.

    38

    What is the Page interface in Spring Data?

    The Page interface is used to represent a page of data. It provides methods to get the content of the page, the page number, the page size, and the total number of elements.

    For more details on pagination in Spring Boot, you can read more about it here.

    39

    What is Spring Caching?

    Spring provides a caching abstraction that allows you to transparently apply caching to your methods. It supports various cache providers like EhCache, Caffeine, and Redis.

    40

    What are the main caching annotations?

    • @EnableCaching: Enables Spring's caching support.
    • @Cacheable: Indicates that the result of a method should be cached.
    • @CachePut: Updates the cache with the result of a method.
    • @CacheEvict: Removes an entry from the cache.
    41

    What is the difference between @Cacheable and @CachePut?

    • @Cacheable: The method is only executed if the cache does not contain the requested entry.
    • @CachePut: The method is always executed, and its result is put into the cache.
    42

    What is Spring WebFlux?

    Spring WebFlux is a reactive web framework that is part of the Spring Framework. It's an alternative to Spring MVC and is designed for building non-blocking, event-driven applications.

    43

    What is the difference between Mono and Flux?

    Mono and Flux are reactive types from the Project Reactor library, which is used by Spring WebFlux.

    • Mono: Represents a stream of 0 or 1 elements.
    • Flux: Represents a stream of 0 to N elements.
    44

    What is the @SpringBootTest annotation?

    The @SpringBootTest annotation is used for integration testing in Spring Boot. It loads the full application context and allows you to test the interaction between different components.

    45

    What is @MockBean?

    The @MockBean annotation is used to add a mock object to the Spring application context. It's useful when you want to mock a specific bean in your integration tests.

    46

    What is the difference between `@Mock` and `@MockBean`?

    • @Mock: A Mockito annotation that creates a mock object. It's used for unit testing.
    • @MockBean: A Spring Boot annotation that adds a mock object to the application context. It's used for integration testing.

    For more details on Spring Boot integration testing, you can read more about it here.

    47

    What are some benefits of using Spring Boot?

    • Convention over Configuration: Spring Boot makes assumptions about how to configure the application, which reduces the amount of manual configuration required.
    • Standalone Applications: You can create self-contained applications that can be run as a simple JAR file.
    • Embedded Servers: Comes with embedded servers, so you don't need to deploy your application to an external server.
    • Production-Ready Features: Provides features like metrics, health checks, and externalized configuration that are useful for production environments.

    For more details on building a complete Spring Boot application with MongoDB and S3, you can read more about it here.

    48

    What is the Spring Expression Language (SpEL)?

    SpEL is a powerful expression language that supports querying and manipulating an object graph at runtime. It can be used in XML or annotation-based Spring configurations.

    49

    What is the difference between ResponseEntity and @ResponseBody?

    • @ResponseBody: An annotation that indicates that the return value of a method should be written directly to the HTTP response body.
    • ResponseEntity: A class that represents the entire HTTP response, including the status code, headers, and body. It gives you more control over the response.
    50

    What is the @ExceptionHandler annotation?

    The @ExceptionHandler annotation is used to handle specific exceptions in a controller. You can use it to define a custom error response for a particular exception.

    51

    What is the difference between @ControllerAdvice and @RestControllerAdvice?

    • @ControllerAdvice: A specialization of the @Component annotation which allows to handle exceptions across the whole application in one global handling component.
    • @RestControllerAdvice: A specialization of @ControllerAdvice that is used for RESTful services. It's a combination of @ControllerAdvice and @ResponseBody.
    52

    What is the Spring Cloud project?

    Spring Cloud provides tools for developers to quickly build some of the common patterns in distributed systems (e.g. configuration management, service discovery, circuit breakers, intelligent routing, micro-proxy, control bus, one-time tokens, global locks, leadership election, distributed sessions, cluster state).

    53

    What is a service discovery and why is it used in microservices?

    Service discovery is the process of automatically detecting devices and services on a network. In a microservices architecture, it's used to allow services to find and communicate with each other without hardcoding the hostnames and ports.

    54

    What is Spring Cloud Gateway?

    Spring Cloud Gateway is a project that provides an API Gateway for microservices. It's built on top of Spring WebFlux and provides features like routing, filtering, and circuit breaking.

    Spring Cloud Gateway Client API Gateway Service A Service B Service C
    55

    What is a circuit breaker and how is it implemented in Spring Cloud?

    A circuit breaker is a design pattern used to detect failures and encapsulates the logic of preventing a failure from constantly recurring. In Spring Cloud, you can use the Resilience4j library to implement the circuit breaker pattern.

    56

    What is Spring Cloud Config?

    Spring Cloud Config provides server-side and client-side support for externalized configuration in a distributed system. With the Config Server, you have a central place to manage external properties for applications across all environments.

    57

    What is Spring Cloud Sleuth?

    Spring Cloud Sleuth is a distributed tracing solution for Spring Cloud. It adds unique IDs to each request that flows through the system, which allows you to trace a request across multiple services.

    58

    What is Spring Batch?

    Spring Batch is a lightweight, comprehensive batch framework designed to enable the development of robust batch applications vital for the daily operations of enterprise systems.

    59

    What is a Job in Spring Batch?

    A Job is an entity that encapsulates an entire batch process. A job is composed of one or more Steps.

    60

    What is a Step in Spring Batch?

    A Step is a domain object that encapsulates an independent, sequential phase of a batch job. Every Job is composed of one or more Steps.

    61

    What is the ItemReader interface?

    The ItemReader is an abstraction that represents the retrieval of input for a Step, one item at a time.

    62

    What is the ItemProcessor interface?

    The ItemProcessor is an abstraction that represents the business processing of an item.

    63

    What is the ItemWriter interface?

    The ItemWriter is an abstraction that represents the output of a Step, one batch or chunk of items at a time.

    64

    What is a chunk-oriented processing in Spring Batch?

    Chunk-oriented processing refers to reading the data one item at a time, and creating 'chunks' that will be written out, within a transaction boundary.

    Spring Batch Chunk-Oriented Processing ItemReader ItemProcessor ItemWriter
    65

    What is the difference between a Tasklet and a Chunk?

    • Tasklet: A simple interface that has one method, execute, which will be called repeatedly until it either returns RepeatStatus.FINISHED or throws an exception to signal a failure.
    • Chunk: A Step that is configured to be chunk-oriented will read and process items in chunks, and then write them out.
    66

    What is the @Scheduled annotation?

    The @Scheduled annotation is used to run a task at a scheduled interval. It can be used to run a Spring Batch job at a specific time or interval.

    67

    What is the difference between fixedRate and fixedDelay in the @Scheduled annotation?

    • fixedRate: The time between the start of each execution.
    • fixedDelay: The time between the end of the previous execution and the start of the next one.
    68

    What is the difference between an ApplicationContext and a BeanFactory?

    • BeanFactory: The root interface for accessing a Spring bean container. It provides basic IoC functionality.
    • ApplicationContext: A sub-interface of BeanFactory. It adds more enterprise-specific functionality, such as the ability to resolve textual messages from a properties file and the ability to publish application events to interested event listeners.
    69

    What is the purpose of the @SpringBootApplication annotation?

    The @SpringBootApplication annotation is a convenience annotation that adds all of the following:

    • @Configuration: Tags the class as a source of bean definitions for the application context.
    • @EnableAutoConfiguration: Tells Spring Boot to start adding beans based on classpath settings, other beans, and various property settings.
    • @ComponentScan: Tells Spring to look for other components, configurations, and services in the specified package, allowing it to find and register the beans.
    70

    What is the difference between JPA and Hibernate?

    • JPA (Java Persistence API): A specification that describes how to manage relational data in Java applications.
    • Hibernate: An implementation of the JPA specification. It's an Object-Relational Mapping (ORM) tool that provides a framework for mapping an object-oriented domain model to a relational database.
    71

    What is the N+1 selects problem in JPA/Hibernate?

    The N+1 selects problem occurs when you fetch a list of entities from the database and then iterate over them, lazily fetching a related entity for each one. This results in one query to fetch the list of entities, and then N additional queries to fetch the related entities.

    N+1 Selects Problem Problem 1. SELECT * FROM author 2. SELECT * FROM book WHERE author_id = ? 3. SELECT * FROM book WHERE author_id = ? ... (N+1 queries) Solution SELECT a.*, b.* FROM author a LEFT JOIN FETCH a.books b (1 query)
    72

    How do you solve the N+1 selects problem?

    You can solve the N+1 selects problem by using a JOIN FETCH clause in your query, or by using a @EntityGraph annotation to specify which associations should be fetched eagerly.

    73

    What is the difference between eager and lazy fetching?

    • Eager Fetching: The related entities are fetched from the database along with the main entity.
    • Lazy Fetching: The related entities are only fetched from the database when they are accessed for the first time.
    74

    What is the @Value annotation?

    The @Value annotation is used to inject values from properties files, system properties, or environment variables into your beans.

    75

    What is the difference between @Value and @ConfigurationProperties?

    • @Value: Used to inject a single value.
    • @ConfigurationProperties: Used to bind a whole set of properties to a Java object. It's generally more type-safe and convenient for working with multiple properties.
    76

    What is a `RestTemplate`?

    RestTemplate is a synchronous client to perform HTTP requests. It's part of the Spring Framework and provides a simple way to communicate with RESTful web services.

    77

    What is a RestClient?

    RestClient is the new synchronous client to perform HTTP requests. Now it is preferred over RestTemplate and has got a fluent API like WebClient.

    For more details on REST clients in Spring, you can read more about it here.

    78

    What is a WebClient?

    WebClient is a non-blocking, reactive client to perform HTTP requests.

    79

    What is the @Async annotation?

    The @Async annotation is used to mark a method as asynchronous. When a method is annotated with @Async, it will be executed in a separate thread.

    80

    How do you enable asynchronous processing in Spring?

    You can enable asynchronous processing by using the @EnableAsync annotation in your configuration class.

    For more details on Spring Boot concurrency and async processing, you can read more about it here.

    81

    What is the ApplicationRunner interface?

    The ApplicationRunner interface is used to execute some code after the Spring Boot application has started. It provides a run method that is called just before SpringApplication.run() completes.

    82

    What is the CommandLineRunner interface?

    The CommandLineRunner interface is similar to ApplicationRunner, but it provides access to the command-line arguments as a string array.

    83

    What is the difference between `ApplicationRunner` and `CommandLineRunner`?

    The main difference is the type of arguments they receive. ApplicationRunner receives an ApplicationArguments object, while CommandLineRunner receives a string array.

    84

    What is the @Conditional annotation?

    The @Conditional annotation is used to indicate that a component is only eligible for registration when all specified conditions match.

    85

    What are some of the built-in conditional annotations?

    • @ConditionalOnClass: The class is loaded if the specified class is on the classpath.
    • @ConditionalOnBean: The class is loaded if the specified bean is present in the ApplicationContext.
    • @ConditionalOnProperty: The class is loaded if the specified property has a certain value.
    86

    What is the purpose of the spring-boot-starter-parent?

    The spring-boot-starter-parent provides default configuration for your Spring Boot application. It includes dependency management for common libraries and plugins, and it sets up the default Java compiler version.

    87

    What is a fat JAR (or über JAR)?

    A fat JAR is a self-contained JAR file that includes all the dependencies required to run an application. Spring Boot creates a fat JAR by default, which makes it easy to run the application as a standalone process.

    88

    What is the difference between server.port and management.server.port?

    • server.port: The port on which the main application runs.
    • management.server.port: The port on which the Actuator endpoints are exposed. It's a good practice to use a different port for management endpoints for security reasons.
    89

    What is the purpose of the @EnableWebMvc annotation?

    The @EnableWebMvc annotation is used to enable Spring MVC configuration. It's typically used in conjunction with a @Configuration class to customize the Spring MVC setup.

    90

    What is the difference between @PathVariable and @RequestParam?

    • @PathVariable: Used to extract values from the URI path.
    • @RequestParam: Used to extract values from the query string.
    91

    What is the `spring.factories` file?

    The spring.factories file is a special file that is used by Spring Boot to load auto-configuration classes. It's located in the META-INF directory of a Spring Boot starter.

    92

    What is the @Lazy annotation?

    The @Lazy annotation is used to initialize a bean lazily. By default, Spring creates all singleton beans at startup. If you annotate a bean with @Lazy, it will only be created when it's first requested.

    93

    What is the purpose of the spring-boot-maven-plugin?

    The spring-boot-maven-plugin provides several features for Spring Boot applications, including:

    • Packaging the application as an executable JAR or WAR.
    • Running the application.
    • Generating build information.
    94

    What is the @Entity annotation in JPA?

    The @Entity annotation is used to mark a Java class as a JPA entity. An entity represents a table in a relational database.

    95

    What is the `@Id` annotation in JPA?

    The @Id annotation is used to specify the primary key of an entity.

    96

    What is the `@GeneratedValue` annotation in JPA?

    The @GeneratedValue annotation is used to specify how the primary key of an entity should be generated. It can be used with different strategies, such as AUTO, IDENTITY, SEQUENCE, and TABLE.

    Summarise

    Transform Your Learning

    Get instant AI-powered summaries of YouTube videos and websites. Save time while enhancing your learning experience.

    Instant video summaries
    Smart insights extraction
    Channel tracking