DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • High-Performance Batch Processing Using Apache Spark and Spring Batch
  • Batch Processing Large Data Sets with Spring Boot and Spring Batch
  • Migrating COBOL Batch to Spring Batch
  • Clustered Quartz Scheduler With Spring Boot and MongoDB

Trending

  • AI’s Role in Everyday Development
  • The Smart Way to Talk to Your Database: Why Hybrid API + NL2SQL Wins
  • How to Format Articles for DZone
  • How to Perform Custom Error Handling With ANTLR
  1. DZone
  2. Culture and Methodologies
  3. Career Development
  4. How To Propagate Context Information Throw Spring Batch

How To Propagate Context Information Throw Spring Batch

Introduction to a framework that performs the propagation of Spring Security, Sleuth, MDC, and Locale (Internationalization) contexts inside Spring Batch items.

By 
Mohammed ZAHID user avatar
Mohammed ZAHID
DZone Core CORE ·
Updated May. 04, 21 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
12.0K Views

Join the DZone community and get the full member experience.

Join For Free

Introduction

While developing applications using Spring batch, especially in a micro-service project, we sometimes face one or most of the following cases:

  • The necessity of getting the security context inside the batch items to call methods that require authorizations inside the same micro-service or perform remote processing by calling other micro-services using Feign Client (HTTP) or  Spring Cloud Stream (broker like Kafka, RabbitMq ...)
  • Propagating Sleuth trace Id and span Id in order to enhance logs traceability inside all the application components including other micro-services so the trace will not be lost if we use Job.
  • Getting the connected user Locale (i18n) in order to generate internationalized output otherwise, all the Job outputs will be generated in the default server language.
  • Retrieving objects stored inside Mapped Diagnostic Context  (MDC) for tracing purposes.

The following schema illustrates remote calls that can be performed in a micro-service-based application and the context information that String Batch items can propagate.


Microservice flow chart

The cases described above can be resolved by passing the context information as job parameters and restoring them before the job or step runs using JobExecutionListener or StepExecutionListener, respectively, according to the execution configuration made (One thread per job or thread pool that).

The problem with this approach is that the code responsible for the job parameters injection will appear with the business one which can cause confusion during code maintenance, also this processing should be transparent for the developers so they can concentrate more on the business logic. This is why I want to introduce a new framework that can be used in order to propagate the contexts described above with the possibility of adding any other information easily.

How It Works

The following diagram describes roughly how this framework works:

  1. An aspect that intercepts the call of JobLauncher.run() method in order to insert the context information as a job parameter.
  2. A customized JobExecutionListener is called by Spring Batch before the start of the Job in order to deserialize the context parameters and put them in the ExecutionContext.
  3. A customized StepExecutionListener is called by Spring Batch before the start of the step in order to restore the context and clear it and the end of the step.

The Job JobExecutionListener and StepExecutionListener are inserted automatically by the framework.

The Job JobExecutionListener and StepExecutionListener are injected and associated automatically with any job by the framework. So no need for extra code.

How To Use It

It's very simple; since the framework is provided with starters, simply add the dependency that corresponds to the needed context.

For Spring Security:

XML
 




x


 
1
<dependency>
2
    <groupId>org.digibooster.spring.batch</groupId>
3
    <artifactId>spring-batch-security</artifactId>
4
    <version>1.0.0</version>
5
</dependency>


For Sleuth:

XML
 




xxxxxxxxxx
1


 
1
<dependency>
2
    <groupId>org.digibooster.spring.batch</groupId>
3
    <artifactId>spring-batch-sleuth</artifactId>
4
    <version>1.0.0</version>
5
</dependency>


For MDC:

XML
 




xxxxxxxxxx
1


 
1
<dependency>
2
    <groupId>org.digibooster.spring.batch</groupId>
3
    <artifactId>spring-batch-mdc</artifactId>
4
    <version>1.0.0</version>
5
</dependency>


For Locale (i18n):

XML
 




x



1
<dependency>
2
    <groupId>org.digibooster.spring.batch</groupId>
3
    <artifactId>spring-batch-locale</artifactId>
4
    <version>1.0.0</version>
5
</dependency>


Advanced Use

In order to propagate a customized context, the developer needs to implement the interface JobExecutionContextListener and inject it as a Spring bean. The new bean will be considered automatically by the framework.

Java
 




x


 
1
/**
2
 * Allow the restoring the context of the thread that runs the job inside the
3
 * job it self.
4
 * 
5
 */
6
public interface JobExecutionContextListener {
7

          
8
    /**
9
     * Serializes the current context information and puts it in the the job
10
     * parameter. This method called by the Aspect {@link JobExecutionAspect}
11
     * 
12
     * @param jobParametersBuilder
13
     */
14
    void insertContextInfo(JobParametersBuilder jobParametersBuilder);
15

          
16
    /**
17
     * Deserializes the context information from the job parameters and inserts it
18
     * in the Job execution context. This method is called by the Job listener
19
     * {@link JobExecutionListenerContextSupport}
20
     * 
21
     * @param jobExecution
22
     */
23
    void fillJobExecutionContext(JobExecution jobExecution);
24

          
25
    /**
26
     * Removes the context information from job execution context when the job ends
27
     * This method is called by the Job listener
28
     * {@link JobExecutionListenerContextSupport}
29
     * 
30
     * @param jobExecution
31
     */
32
    void removeFromJobExecutionContext(JobExecution jobExecution);
33

          
34
    /**
35
     * Restore the context information from the job execution context before each
36
     * step This method is called by the Step listener
37
     * {@link StepExecutionListenerContextSupport}
38
     * 
39
     * @param stepExecution
40
     */
41
    void restoreContext(StepExecution stepExecution);
42

          
43
    /**
44
     * Remove the context information when the step ends This method is called by
45
     * the Step listener {@link StepExecutionListenerContextSupport}
46
     * 
47
     * @param stepExecution
48
     */
49
    void clearContext(StepExecution stepExecution);
50

          
51
}


The framework source code is published in github

Spring Framework Spring Batch career

Opinions expressed by DZone contributors are their own.

Related

  • High-Performance Batch Processing Using Apache Spark and Spring Batch
  • Batch Processing Large Data Sets with Spring Boot and Spring Batch
  • Migrating COBOL Batch to Spring Batch
  • Clustered Quartz Scheduler With Spring Boot and MongoDB

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!