The concept of the scope of a bean in spring enables us to focus on business logic without having to worry about data inconsistency.

The lifespan of beans in a spring application are defined with respect to the application context(@Singleton), thread (@Prototype), or incase of web-aware applications http session (@Session), http request (@Request) or servlet lifecycle (@ApplicationScope), webSocket session.

In other words, a bean annotated with @Singelton will be created once when the container is initialized (Application is started) and is destroyed when the container is terminated (Application is shut down).

Similarly, a bean annotated with @prototype is created every time there is a new request for the bean. Bean annotated with @Session is created once per session and a bean annotated with @Request is created for every http request.

As can be seen, we have a large bevy of bean scopes to choose from for every custom application need. We have specific scopes pertaining to web applications, we have scopes pertaining to application contexts.

So far so good. But in the case of a spring batch job, the above-mentioned scopes can be used only up to a certain extent. As a SpringBatch Job comprises of steps thus it is only natural and practical to define beans with respect to a step in addition to be the above-mentioned scopes.

Luckily for us, Spring defines two more scopes namely step scope and job scope that help us in defining beans whose lifecycles are tied to the lifecycle of a job and a step respectively.

#scopes #springbatch #java #step scoped beans in a spring batch job #spring batch job #spring

Step scoped beans in a Spring Batch Job
4.55 GEEK