CDI @RequestScoped context is often used as a thread related context (kind of abstracted ThreadLocal). However there are several environments where it is not defined and therefore not active/usable.

Most of other specifications try to enforce it is started implictly and therefore usable but it is almost never the case with 3rd party libraries.

To ensure you can still use your CDI beans with in any environment, CDI introduced in its 2.0 release a new API: the RequestContextController.

Its API is super simple: activate() and deactivate() and it just makes a request context active in current thread.

In JBatch for instance, the request scope is not active in steps by default in steps but it can be very interesting to get it to reuse the logic you already have in your "core". One common example will be an EntityManager which is produced in @RequestScoped which wouldn't be usable in a chunk writer in jbatch.

To solve it you just implement a ChunkListener which get injected the RequestContextController and you start/stop the context in the corresponding hooks:

@Named
@ApplicationScoped // any scope works here actually
public class ScopeActivator implements ChunkListener {
    @Inject
    private RequestContextController requestContextController;

    @Override
    public void beforeChunk() throws Exception {
        requestContextController.activate();
    }

    @Override
    public void afterChunk() throws Exception {
        requestContextController.deactivate();
    }

    @Override
    public void onError(final Exception e) throws Exception {
        afterChunk();
    }
}

Then you register it in your batch definition (xml):

<?xml version="1.0" encoding="UTF-8"?>
<job id="sample" version="1.0"
     xmlns="http://xmlns.jcp.org/xml/ns/javaee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="
      http://xmlns.jcp.org/xml/ns/javaee
      http://xmlns.jcp.org/xml/ns/javaee/jobXML_1_0.xsd">
  <step id="test">
    <listeners>
      <listener ref="scopeActivator" />
    </listeners>
    <chunk>
      <!-- your chunk -->
    </chunk>
  </step>
</job>

And now you can use your entity manager in your chunk :).

This simple example is actually not rare, integrating with RxJava or any "reactive" framework will often require such integration code and CDI 2.0 completly assumes it with its new API!

From the same author:

In the same category: