Spring Boot Interview Materials
Spring
Bean Scope
There are
5 types of spring bean scopes:
- Singleton - only one instance of the spring bean will be created for
the spring container. This is the default spring bean scope. While using this
scope, make sure bean doesn’t have shared instance variables otherwise it might
lead to data inconsistency issues.
- Prototype – A new instance will be created every time the bean is
requested from the spring container.
- Request – This is same as prototype scope, however it’s meant to
be used for web applications. A new instance of the bean will be created for
each HTTP request.
- Session – A new bean will be created for each HTTP session by the
container.
- Global-session – This is used to create global session beans for Portlet
applications
Why to use
the MVC Pattern?
1) Separation of Concerns -Separation of Concern is one of the
core advantages of an MVC Pattern. The MVC pattern provides a clean separation
between the UI, Business Logic, Model or Data. On the other hand, we can also
say it provides a separation of Programming logics for various components.
2) Easy to modify – Because of the separation of responsibilities,
future development or modification becomes easier and in turn it increases the
scalability of the software.
3) Simultaneous development — multiple developers can work
simultaneously on the model, controller and views separately as per their area
of expertise.
4) Low coupling — The MVC pattern offers low coupling between its
components.
5) High cohesion — It provides high cohesion such as it enables logical grouping of related actions on a controller together. The views for a specific model are also grouped together.
Spring Boot Annotations and their use cases
Spring Boot Annotations are the metadata that provides the additional formation about a Spring Boot program. Several spring boot annotations provide different automatic configurations.
Below are all the essential spring boot annotations you should know about.
1] @Bean
The “@Bean” is a method-level annotation that is analogous to XML <bean> tag. When you declare this annotation, Java creates a bean with the method name and registers it with the BeanFactory. The following shows how the usage of @Bean in a method statement:
@Bean public ExampleBean exampleBean() { return new ExampleBean(); }
2] @Springbootapplication
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MyClass {
public static void main(String[] args) {
SpringApplication.run(MyClass.class, args);
}
}
3] @Configuration
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ConfigClass {
@Bean
public MyBean mybean() {
return new MyBean();
}
}
4] @ComponentScan
package TestPackage;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = "TestPackage")
public class TestClass {
}
5] @EnableAutoconfiguration
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
@EnableAutoConfiguration
public class TestClass {
public static void main(String[] args) {
SpringApplication.run(TestClass.class, args);
}
}
6] @RequestMapping
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class ControllerClass {
@ResponseBody
@RequestMapping("/cart")
public String getCart() {
return "this is the cart!";
}
@ResponseBody
@RequestMapping("/catalogue")
public String getCatalogue() {
return "this is the catalogue";
}
}
7] @GetMapping
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@GetMapping("/hello")
public String hello() {
return "Hello Spring Boot!";
}
}
8] @RequestParam
@GetMapping("/api/book")
@ResponseBody
public String getBook(@RequestParam String id) {
return "Book ID: " + id;
}
9] @Service
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class BankService {
private final BankInfo bankInfo;
@Autowired
public BankService(BankInfo bankInfo) {
this.bankInfo = bankInfo;
}
}
10] @Component
import org.springframework.stereotype.Component;
@Component
public class TestComponentAnnotation {
public int multiply(int x, int y) {
return x * y;
}
}
11] @Repository
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.howtodoinjava.demo.model.BookEntity;
@Repository
public interface BookRepository extends JpaRepository<BookEntity, Long>
{
}
12] @Controller
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class TestController {
@RequestMapping("/hello")
public String hello()
{
return "Hello Spring!";
}
}
13] @Autowired
import org.springframework.beans.factory.annotation.Autowired;
public class Product {
private Product product;
@Autowired
public void setProduct( Product product ){
this.product = product;
}
public Product getProduct( ) {
return product;
}
}
14] @SpringBootTest
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
public class DemoTest
{
@Autowired
private DemoController demoController;
@Test
public void contextLoads() throws Exception {
assertThat(demoController).isNotNull();
}
}
15] @MockBean
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
@RunWith(SpringRunner.class)
@SpringBootTest
public class ProductServiceTest {
@Autowired
private ProductService productService;
@MockBean(name="Product")
private Product product;
@Test
public void test(){
when(product.findAll()).thenReturn(Collections.emptyList());
assertTrue(productService.findAll().isEmpty());
}
}
@Bean — method annotated with @Bean creates and returns Bean. Spring Container calls such methods, automatically.
@Configuration — Class annotated with @Configuration has methods annotated with @Bean or has data members annotated with @Value
@Scope — Indicates Scope of a Bean such as Singleton, Prototype,
Session, Request , Global-Session
@Lazy — Indicates that Bean needs to be created on Demand only, i..e when there is explicit request
@Autowired — Indicates Bean needs to be automatically created by Spring Container.
@Qualifier — Used along with @Bean or @Autowired to avoid ambiguity during Bean creation by Spring Container
@Primary — When there are multiple qualified Beans, priority is given to the Bean annotated with @Primary
@Component — Indicates a class as Component, so that it can be recognized by @ComponentScan, automatically. As known, all Component classes are automatically scanned and loaded by Spring Container.
@ComponentScan — Scans one or more packages/subpackages for Components.
@Service — Components in Service Layer need to be annotated with @Service
@Repository — Components in Repository Layer need to be annotated with @Repository
@SpringBootApplication — This annotation is used with main class of Spring Boot
Application its triggers auto-configuration and component
scanning
The @SpringBootApplication is a combination of three annotations @Configuration (used for Java-based configuration), @ComponentScan (used for component scanning), and @EnableAutoConfiguration (used to enable auto-configuration in Spring Boot).
@Value — Data members of a Configuration class are automatically loaded from Configuration file(such as application.properties)
@ConfigurationProperties — Class annotated with @ConfigurationProperties
automatically loads data members(with matching name)from Configuration
file(such as application.properties)
REST
API related Annotations:
@RestController — Class annotated with @RestController has REST end points.
@RequestBody — used with method parameter of REST end point. This annotation automatically deserializes the body(of Http request) into a Model or Entity object.
@PathVariable — used with method parameter of REST end point. It automatically retrieves a Path variable into the method parameter of REST end point.
@RequestParam — used with method parameter of REST end point. It automatically retrieves a Query parameter into the method parameter of REST end point.
@RequestHeader — used with method parameter of REST end point. It automatically retrieved value from a specified HTTP header and populates the value into the method parameter.
REST End points are annotated with any of below annotation, to indicate specific HTTP method
@RequestMapping:- map HTTP requests to REST and MVC controller methods
@GetMapping
@PostMapping
@PutMapping
@DeleteMapping , etc…
@ControllerAdvice, @ExceptionHandler — to Handle REST API Exceptions
@Valid — used with
@RequestBody , to automatically validate the data members during
deserialization. This annotation works along with Validation rules such as
@NotNull, @Max, etc…
Spring
Boot Data JPA related annotations:
@Entity — class which need to be mapped with underlying DB Table
@Table — Used along with @Entity annotated, to specify custom name for DB Table(by default DB Table has same name as Entity Class name)
@Column — Used with Data members of Entity class, to indicate a Column of DB Table.
Data field Validation related — @NotNull, @Max, @Min, @Positive, @Negative, etc…
@Query — to specify Custom Query String(native or JPQL query), along with method declaration in Repository interface.
Entity class relationships — @OnetoOne, @OnetoMany, @ManytoOne, @ManytoMany
Security related Annotations:
@CrossOrigin — Can be used with Class or method(s), indicating by which Origins(domain
name or domain name patterns) the REST end points can be invoked.
Below annotations used for method level Security
@Secured, @PreAuthorize, @PermitAll
AOP related Annotations: Aspect Oriented Programming
is used to separate Cross Cutting concerns(such as Logging, Security, etc…), from Business Logic. AOP is used only in selected Spring Boot
Projects.
@Aspect — to specify that a class is Aspect, which holds Cross cutting concerns
@Pointcut — to specify Pointcut expressions
@Before — to specify a method is Before Advice
@After — to specify a method is After Advice
@Around — to specify a
method is around Advice
Caching
related Annotations:
@EnableCaching — Used along with @SpringBootApplication, which enables the application to perform Cache related operations
@Cacheable — Adds an entry to the Cache
@CachePut — Updates an existing entry in the Cache
@CacheEvict — Removes one or more entries from the Cache
Transaction
related Annotations:
@Transactional — Used by class/interface or method, indicates the method(s) is executed
under a Transaction
a) spring-boot-starter-web —
includes Spring Core, MVC, REST API related dependencies, including Apache
Tomcat Web Server
b) spring-boot-starter-data-jpa —
includes Hibernate ORM and related Spring Boot functionality to interact with
RDBMS databases
c) spring-boot-starter-validation — provides validation related functionality
d) spring-boot-starter-test — provides Test related functionality
e) spring-boot-starter-aop — provides Aspect Oriented programming
f) spring-boot-starter-security — provides Authentication, Authorization, Security Filters
g) spring-boot-starter-actuator — provides actuator which is useful in remote health monitoring of running Spring Boot application
h) spring-boot-devtools — provides remote debugging, automatic live reload of project, whenever source code changes are saved(this saves development time, by avoiding manual restart of running project)· These
annotations are used to create Spring beans automatically in the application
context (Spring IoC Container)
· The main
stereotype annotation is @Component
· By using
this annotation Spring provide more stereotype meta annotation such as
@Service, @Repository & @Controller
· @Service
annotation is used to create bean at Service layer
· @Repository
annotation is used to create a bean at the DAO layer
· @Controller
is used to create bean at the controller layer
Explain how you can override the default
properties of Spring boot projects.
By specifying
properties in the application.properties file, it is possible to override the
default properties of a spring boot project.
Example:
In Spring MVC applications, you need to specify a suffix and prefix. You can do
this by adding the properties listed below in the application.properties
file.
·
For
suffix – spring.mvc.view.suffix: .jsp
·
For
prefix – spring.mvc.view.prefix: /WEB-INF
What issues are generally solved by spring
clouds?
The following
problems can be solved with spring cloud:
- Complicated
issues caused by distributed systems: This includes network issues, latency problems,
bandwidth problems, and security issues.
- Service
Discovery issues: Service
discovery allows processes and services to communicate and locate each other
within a cluster.
- Redundancy
issues: Distributed
systems can often have redundancy issues.
- Load
balancing issues: Optimize
the distribution of workloads among multiple computing resources, including
computer clusters, central processing units, and network links.
- Reduces
performance issues: Reduces
performance issues caused by various operational overheads.
What do you mean by Cohesion and Coupling?
Cohesion: It is defined as a
relationship between two or more parts/elements of a module that serves the
same purpose. Generally, a module with high cohesion can perform a specific
function efficiently without needing communication with any other modules. High
cohesion enhances the functionality of the module.
Explain the term Eureka in Microservices.
Eureka Server,
also referred to as Netflix Service Discovery Server, is an application that
keeps track of all client-service applications. As every Microservice registers
to Eureka Server, Eureka Server knows all the client applications running on
the different ports and IP addresses. It generally uses Spring Cloud and is not
heavy on the application development process.
What is the main role of docker in
microservices?
Docker generally provides
a container environment, in which any application can be hosted. This is
accomplished by tightly packaging both the application and the dependencies
required to support it. These packaged products are referred to as Containers,
and since Docker is used to doing that, they are called Docker containers.
Docker, in essence, allows you to containerize your microservices and manage
these microservices more easily.
Difference between @Bean and @Component
Key |
@Bean |
@Component |
|
Auto detection |
It is used to
explicitly declare a single bean, rather than letting Spring do it
automatically. |
If any class is
annotated with @Component it will be automatically detect by using classpath
scan. |
|
Spring Container |
Bean can be created
even class is outside the spring container |
We can’t create bean
if class is outside spring container |
|
Class/Method
Level Annotation |
It is a method level
annotation |
It is a class level
annotation |
|
@Configuration |
It works only when
class is also annotated with @Configuration |
It works without |
|
Use Case |
We should use @bean,
if you want specific implementation based on dynamic condition. |
We can’t write
specific implementation based on dynamic condition |
Spring boot JWT questions
1] What is JWT?
How to implement?
JSON Web Token (JWT) is an open standard (RFC
7519) that specifies a compact and self-contained way of transmitting
information securely as a JSON object between parties. This information can be
verified and trusted as it has been digitally signed. It can also hold all the
user's claim, like authorization information, so that the service provider does
not need to access the database to validate user roles and permissions for each
request; data is extracted from the token.
2] What is Workflow
of JWT?
- Customers sign in by
submitting their credentials to the provider.
- Upon successful
authentication, it generates JWT containing user details and privileges for
accessing the services and sets the JWT expiry date in payload.
- The server signs and
encrypts the JWT if necessary and sends it to the client as a response with
credentials to the initial request.
- Based on the expiration set
by the server, the customer/client stores the JWT for a restricted or infinite
amount of time.
- The client sends this JWT
token in the header for all subsequent requests.
- The client authenticates
the user with this token. So we don't need the client to send the user name and
password to the server during each authentication process, but only once the
server sends the client a JWT.
3] What is the structure of
JWT?
JWT consists of 3 parts – Header => Payload => Signature
It generate JWT token as in the form of a.b.c which represent header.payload.signature
·
Header: contains details about the type of
the token and the algorithm used to sign the content.
·
Payload: holds the actual data that we want
to send. It is not recommended to put sensitive data (emails, passwords) in the
payload.
·
Signature: ensures that the token is
trustworthy and not changed along the way to the destination.
4] What is
expiration date of JWT?
The JWT access token is only valid for a limited period of time. Using an
expired JWT would cause the operation to fail. This value is normally 1200
seconds or 20 minutes.
5] How
do we specify expiration date of JWT?
private String doGenerateToken(Map<String, Object> claims, String subject) {
return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(new Date(System.currentTimeMillis() + jwtExpirationInMs)).signWith(SignatureAlgorithm.HS512, secret).compact();
}
6] What are the advantages of JWT?
- Good
Performance: JWT itself contains all information, so we don't have to go to
Authorization server to get the user's information to verify whether user is
valid or not.
- Portable:
Allow to use multiple backends with single access token.
- It is Very
Mobile Friendly, because cookies are not required.
- JWT contains
expiration date as a claim that can be used to determine when the access token
is going to expire.
- It's very
secure way to validate the user information, as it's digitally signed.
- It's
digitally signed, so if anyone updates it the server will know about it.
- It is most
suitable for Microservices Architecture.
- It has other
advantages like specifying the expiration time.
7] What is
OAuth and JWT?
JWT is essentially a token format. JWT is a token
that can be used as part of the OAuth authorization protocol. Server-side and
client-side storage are used in OAuth. If you want to make a proper logout,
you'll need to use OAuth2. Authentication with a JWT token does not allow you
to logout.
8] Is JWT required while communicating over HTTPS?
The JWT is signed with public/private key pairs to ensure that the sender is authenticated and that the payload has not been tampered with. The JSON Web Token, on the other hand, is in plain text.
To encrypt communication, we will require SSL/HTTPS. Attackers can intercept network traffic without SSL/HTTPS and extract the JWT, making your application vulnerable to man in the middle attacks.9]
Why JWT is a stateless
authentication?
JSON Web Tokens (JWT) are called stateless because the authorizing server
doesn't need to keep track of anything, the token is all that's required to
verify a token bearer's authorization. In stateless authentication, no need to
store user information in the session.
10]
What is
AbstractSecurityInterceptor in Spring Security?
The AbstractSecurityInterceptor in Spring Security handles the initial
authorization of an incoming request.
There are two concrete implementations of the AbstractSecurityInterceptor:
1->FilterSecurityInterceptor
The Spring Security filter chain's default filter. All authenticated user requests will be authorised by the FilterSecurityInterceptor.
2->MethodSecurityInterceptor
11]
What is Spring Boot
Method-Level Security?
The @PreAuthorize annotation is used on controller methods to implement
method-level security. This annotation comprises a snippet of Spring Expression
Language (SpEL) that is evaluated to determine whether the request should be
authenticated.
12] What
is difference of using @PreAuthorize and @Secured in Spring Security?
@PreAuthorize annotation is used to check for authorization before executing the method.
We could alternatively use the @Secured annotation in spring to handle method-level security, however it has several limitations, such as
1-> We cannot have several conditions with the @Secured annotation,
i.e. the roles cannot be coupled with an AND/OR condition.
2-> Spring expression language is not supported by the @Secured
annotation.
13] What
is the difference between hasRole() and hasAuthority()?
Spring roles are authorities with the ROLE_prefix. Another thing to understand of it is that roles are meant for broad sets of permissions, whereas authorities are meant for finer-grained management. However, that is only one possible usage. The developer is in charge of the actual implementation. In this tutorial, authorities are used to map to authorization groups.
@PreAuthorize("hasAuthority('Admin')")
@RequestMapping("/fetch-users")
@ResponseBody
public String protectedUserPage() {
return "TechGeekNext User";
}
The crucial thing to remember is that in order to use hasRole(), the
authority name in the claim must begin with ROLE_. You might, for example, use
hasRole('ADMIN') if you created a ROLE ADMIN group and added your user to it.
14] What
is difference between Spring Security's @PreAuthorize and HttpSecurity?
- The first
distinction is small, but it is important to note. Before controller mapping
occurs, the HttpSecurity function rejects the request in a web request filter.
The @PreAuthorize assessment, on the other hand, occurs later, directly before
the controller method is executed. This means that HttpSecurity configuration
is done before @PreAuthorize.
- Second,
HttpSecurity is associated with URL endpoints, whereas @PreAuthorize is
associated with controller methods and is located within the code next to the
controller definitions.
- The use of
SpEL (Spring Expression Language ) is another advantage that @PreAuthorize has
over HttpSecurity.
Spring Batch Interview Questions
1. What is Spring Batch?
2. What are the main components of Spring Batch?
Answer: The main components are:
- Job: Represents the batch process.
- Step: A phase in a batch job.
- JobInstance: The job's definition.
- JobExecution: The runtime instance of a job.
- StepExecution: The runtime instance of a step.
3. What is a JobLauncher in Spring Batch?
run
method that takes Job
and JobParameters
as arguments.4. Explain the difference between Tasklet and Chunk-oriented processing.
- Tasklet: A single unit of work to be executed in one go.
- Chunk-oriented processing: Processes a set of items (chunks) together. It reads, processes, and writes in chunks.
5. How do you configure a Spring Batch job?
6. What is the role of JobRepository in Spring Batch?
7. How can you handle transaction management in Spring Batch?
8. What are Listeners in Spring Batch, and why are they used?
JobExecutionListener
, StepExecutionListener
, and ChunkListener
.9. How does Spring Batch handle job restartability?
Answer: Spring Batch maintains the state of job executions using JobRepository. If a job fails, it can be restarted from the last committed point. The framework supports job restart by identifying incomplete jobs and resuming from where it left off.
10. What is SkipPolicy, and how is it used?
Answer: SkipPolicy is used to define conditions under which processing errors can be skipped and the job can continue. It can be configured to skip certain exceptions a specific number of times.
11. Describe a scenario where you would use Spring Batch.
Answer: Spring Batch is ideal for scenarios such as:
- Migrating large datasets between databases.
- Batch processing for end-of-day financial transactions.
- Generating reports from large datasets.
- ETL (Extract, Transform, Load) operations.
12. How would you configure a Spring Batch job to read from a database and write to a CSV file?
Answer:
- Reader: Configure a
JdbcCursorItemReader
to read data from the database. - Processor: Optionally, process the data using an
ItemProcessor
. - Writer: Use a
FlatFileItemWriter
to write data to a CSV file. - Define the job and steps using either XML or Java configuration.
13. What approach would you take to ensure data integrity during batch processing?
Answer: Ensure data integrity by:
- Implementing proper transaction management.
- Using chunk-oriented processing to handle large volumes safely.
- Configuring
SkipPolicy
andRetryPolicy
appropriately. - Writing comprehensive tests to validate batch jobs.
14. What are some best practices for designing Spring Batch jobs?
Answer:
- Modularity: Design jobs and steps to be reusable and modular.
- Error Handling: Implement robust error handling and retry mechanisms.
- Monitoring: Use listeners and job repository to monitor job execution.
- Resource Management: Optimize resource usage, especially for large data volumes.
- Documentation: Document job configurations and business logic for maintainability.
15. What is the role of ItemReader, ItemProcessor, and ItemWriter in Spring Batch?
Answer:
- ItemReader: Responsible for reading data from a source. Examples include
FlatFileItemReader
,JdbcCursorItemReader
, andJpaPagingItemReader
. - ItemProcessor: Used to process data after it is read. It allows for transforming data, filtering, or applying business logic.
- ItemWriter: Writes processed data to a destination. Examples include
FlatFileItemWriter
,JdbcBatchItemWriter
, andJpaItemWriter
.
16. How can you achieve parallel processing in Spring Batch?
Answer: Parallel processing can be achieved by:
- Using multiple threads within a step (
TaskExecutor
). - Partitioning a step to run in parallel across multiple instances.
- Configuring multiple jobs to run concurrently.
17. What is a Partitioned Step in Spring Batch, and how does it work?
Answer: A Partitioned Step divides a large task into smaller partitions that can be processed concurrently. Each partition is assigned to a separate thread or node. It is configured using Partitioner
and StepExecutionSplitter
.
18. Explain the use of JobParameters
in Spring Batch.
Answer: JobParameters
are used to pass parameters to a job at runtime. They ensure that each job instance is uniquely identified, allowing for the same job to be executed multiple times with different parameters.
19. What is a JobExecutionDecider, and how is it used?
Answer: JobExecutionDecider
allows for dynamic decision-making within a job flow. It evaluates conditions and determines the next step to execute based on custom logic.
20. How do you implement retry logic in Spring Batch?
Answer: Retry logic is implemented using RetryPolicy
and RetryTemplate
. It allows you to retry an operation a specified number of times if certain exceptions occur.
21. What is a CompositeItemProcessor, and when would you use it?
CompositeItemProcessor
is a processor that delegates to a list of other processors. It allows for chaining multiple processors together in a sequence. It's useful when you need to apply multiple transformations to the data.22. How can you handle large data sets in Spring Batch without running into memory issues?
Answer: Handle large data sets by:
- Using chunk-oriented processing to process data in manageable chunks.
- Optimizing ItemReader to read data in smaller batches.
- Configuring proper transaction boundaries to ensure efficient resource management.
23. What is the significance of JobIncrementer
in Spring Batch?
Answer: JobIncrementer
is used to generate unique job instance identifiers. It ensures that each job instance is uniquely identified and can be restarted or monitored independently.
24. Explain the role of StepScope
in Spring Batch.
Answer: StepScope
is a Spring Scope that defines the lifecycle of beans to be limited to a single step execution. It helps manage resources and data specific to a step.
25. How do you skip records in Spring Batch, and why would you do it?
Answer: Skipping records is achieved using SkipPolicy
and SkipListener
. You skip records that cause exceptions, allowing the job to continue processing other records. This is useful when encountering corrupt or invalid data.
26. What are the different types of job repositories in Spring Batch?
Answer: Spring Batch supports two types of job repositories:
- In-memory Job Repository: Suitable for development and testing.
- Database Job Repository: Suitable for production, as it persists job execution data in a database.
27. How can you monitor and manage Spring Batch jobs?
Answer: Monitoring and managing jobs can be done through:
- Using
JobExplorer
andJobOperator
to query and manipulate job executions. - Implementing custom listeners to log job and step execution details.
- Integrating with Spring Batch Admin or other monitoring tools for real-time insights.
28. What is a JobExecutionListener
and how is it used?
Answer: JobExecutionListener
is an interface for receiving callbacks before and after a job execution. It can be used to perform actions like logging, sending notifications, or setting up resources.
29. How do you handle multiple data sources in a Spring Batch job?
Answer: Handle multiple data sources by configuring multiple ItemReader
and ItemWriter
beans, each pointing to a different data source. Use Spring's @Primary
annotation to specify the default data source if needed.
30. What are the strategies for handling job failures in Spring Batch?
Answer: Strategies for handling job failures include:
- Implementing retry and skip logic.
- Configuring job restartability to resume from the last successful step.
- Using listeners to capture and log error details.
- Implementing robust exception handling within steps.
Comments
Post a Comment