【问题标题】:How to inject ApplicationScoped bean in Stateless bean?如何在无状态 bean 中注入 ApplicationScoped bean?
【发布时间】:2015-11-20 12:53:22
【问题描述】:

我有调用异步操作的无状态 bean。我想将我的另一个 bean 注入到这个 bean 中,它存储(或者更确切地说应该存储)正在运行的进程状态。这是我的代码:

处理器:

@Stateless
public class Processor {

    @Asynchronous
    public void runLongOperation() {
        System.out.println("Operation started");
        try {
            for (int i = 1; i <= 10; i++) {
                //Status update goes here...
                Thread.sleep(1000);
            }
        } catch (InterruptedException e) {
        }
        System.out.println("Operation finished");
    }

}

处理器处理程序:

@ManagedBean(eager = true, name="ph")
@ApplicationScoped
public class ProcessorHandler implements RemoteInterface {

    public String status;

    @EJB
    private Processor processor;

    @PostConstruct
    public void init(){
        status = "Initialized";
    }

    @Override
    public void process() {
        processor.runLongOperation();
    }

    public String getStatus() {
        return status;
    }


}

ProcessHandler 的Process 方法绑定到一个按钮。 我想从处理器内部修改 ProcessHandler bean 的状态,以便向用户显示更新的状态。

我尝试使用@Inject、@ManagedProperty 和@EJB 注释,但没有成功。

我正在使用 Eclipse EE 开发的 Websphere v8.5 上测试我的解决方案。


将注入添加到处理器类时...

@Inject
public ProcessorHandler ph;

我收到错误:

The @Inject java.lang.reflect.Field.ph reference of type ProcessorHandler for the <null> component in the Processor.war module of the ProcessorEAR application cannot be resolved.

【问题讨论】:

  • 那么我应该如何处理这个问题?你能给我一些建议吗?

标签: jsf ejb


【解决方案1】:

您应该从不在您的服务层 (EJB) 中有任何特定于客户端的工件(JSF、JAX-RS、JSP/Servlet 等)。它使服务层无法跨不同的客户端/前端重用。

只需将private String status 字段移动到 EJB 中,因为它实际上是负责管理它的人。

@ManagedBean(eager = true, name="ph")
@ApplicationScoped
public class ProcessorHandler implements RemoteInterface {

    @EJB
    private Processor processor;

    @Override
    public void process() {
        processor.runLongOperation();
    }

    public String getStatus() {
        return processor.getStatus();
    }

}

请注意,这不适用于 @Stateless,但仅适用于 @SingletonStateful,原因很明显。

【讨论】:

  • 酷!我现在就试试。谢谢你的建议:)
  • @Tiny:因为它们应该是无状态的(即没有任何实例变量)。也就是说,容器不能保证跨方法调用重复使用完全相同的无状态 EJB 实例。另见 a.o. stackoverflow.com/a/31639830
  • 呃!我现在看到,“只需将 private String status 字段移入 EJB”,这是我之前完全错过的。谢谢。
  • 我按照您的建议修改了我的解决方案。状态现在存储在处理器 @Sigleton ejb 中,并且异步方法从处理器对象的另一个 bean(@Stateless,方法是 @Asynchronous)调用。再次感谢您的建议!
猜你喜欢
  • 2015-01-04
  • 1970-01-01
  • 2013-03-05
  • 1970-01-01
  • 1970-01-01
  • 2016-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多