Java EE 7 - Injection into Runnable/Callable object

非 Y 不嫁゛ 提交于 2020-01-02 01:25:28

问题


Concurrency Utilities(JSR 236) has been introduced in Java EE 7.

Is there any way how to inject my EJBs into Runnable/Callable object?

Specifically I want something like this:

ejb with business logic

@LocalBean
public class MyEjb {
    public void doSomeStuff() {
        ... do some stuff ...
    }
}

runnable/callable class where I want to inject instance of MyEjb

public class MyTask implements Runnable {
    @EJB
    MyEjb myEjb;

    @Override
    public void run() {
        ...
        myEjb.doSomeStuff();
        ...
    }
}

Object which starts the new task

@Singleton
@Startup
@LocalBean
public class MyTaskManager {
    @Resource
    ManagedExecutorService executor;

    @PostConstruct
    void init() {
        executor.submit(new MyTask());
    }
}

myEjb field in MyTask is always null. I suppose there could help JNDI lookup, but is there any proper way how to do this?


回答1:


You have to give the container a chance to inject the EJB into your Task instance. You can do this by using a dynamic instance like in this code:

@Stateless
public class MyBean {
    @Resource
    ManagedExecutorService managedExecutorService;
    @PersistenceContext
    EntityManager entityManager;
    @Inject
    Instance<MyTask> myTaskInstance;

    public void executeAsync() throws ExecutionException, InterruptedException {
    for(int i=0; i<10; i++) {
        MyTask myTask = myTaskInstance.get();
        this.managedExecutorService.submit(myTask);
    }
}

Because you don't create the instance with the new operator but rather over CDI's instance mechanism, the container prepares each instance of MyTask when calling myTaskInstance.get().




回答2:


The EJB can not be injected if the MyTask instance is created by you because the Container knows only instances created by itself. Instead you can inject the EJB in the MyTaskManager Singleton SB and define your MyTask Runnable class as innerclass as follow:

@Singleton
@Startup
@LocalBean
public class MyTaskManager {
    @Resource
    ManagedExecutorService executor;

    @EJB
    MyEjb myEjb;

    @PostConstruct
    void init() {
        executor.submit(new MyTask());
    }

    class MyTask implements Runnable {
        @Override
        public void run() {
            ...
            myEjb.doSomeStuff();
            ...
        }
    }
}


来源:https://stackoverflow.com/questions/21078616/java-ee-7-injection-into-runnable-callable-object

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