Java EE 7 - 注入Runnable / Callable对象 [英] Java EE 7 - Injection into Runnable/Callable object

查看:122
本文介绍了Java EE 7 - 注入Runnable / Callable对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java EE 7中引入了并发实用程序(JSR 236)。

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

有没有办法将我的EJB注入Runnable / Callable对象?

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

特别是我想要这样的东西:

Specifically I want something like this:

ejb with business logic

ejb with business logic

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

runnable / callable class我想注入MyEjb的实例

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();
        ...
    }
}

启动对象新任务

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

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

MyTask中的myEjb字段始终为空。我想可以帮助JNDI查找,但有没有正确的方法如何做到这一点?

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

推荐答案

你必须给容器有机会将EJB注入您的Task实例。您可以使用此代码中的动态实例来执行此操作:

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);
    }
}

因为你没有用新的创建实例运算符,而不是CDI的实例机制,容器在调用 myTaskInstance.get()时准备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().

这篇关于Java EE 7 - 注入Runnable / Callable对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆