What is the intended purpose of @JobScope in Spring Batch? What's the intended way to share in-memory data between steps?

只愿长相守 提交于 2021-02-19 08:53:25

问题


I'm using it today to cache objects between steps so that I don't have to build the entire job in a single step. At first, since my Steps were not annotated with any scope (though it's hard to make sense of them not implicitly being @JobScope) I ran into some gnarly unit testing issues claiming:

Scope 'job' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No context holder available for job scope

I read (on the since abandoned Gitter thread (which was very informative)) that this may not be the right use case for @JobScope. Indeed I'm concerned now that the job scope is per thread somehow.

This leads me to the question of what is the purpose of @JobScope, if I really am misusing it? And if I'm misusing it what is the right way to share data between Steps in the same job without writing to a database table/temporary file only to turn around and read it at the start of the next step?
As a side note: (and Spring Batch is no different than other frameworks in this regard) these questions stem from the available examples being too simplistic to have much bearing on real-world use.


回答1:


JobScope in 90%+ of cases is a code smell. It's why we avoided adding it for so many years. It was really only added to Spring Batch because the feature was required for the JSR-352 implementation.

The "right" way to share data between steps is via a proper data store of some kind (db of some kind, NoSQL store, files, etc). If your job goes down, you'd want that data to be available on a restart, which sharing those values in memory via a JobScope defined cache would not enable. If you have large amounts of data, you'd want to persist that somewhere to be economical with your memory usage. Also, as you've noted, the JobScope (just like the StepScope) is not available to all threads (since we don't manage all the threads in a job, there's no practical way to make that happen) so it limits its usefulness.

In the end, I have yet to find a use case where I've said that the JobScope is the right way to handle a given use case, this one included.



来源:https://stackoverflow.com/questions/60642390/what-is-the-intended-purpose-of-jobscope-in-spring-batch-whats-the-intended-w

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!