如何在无状态 bean 中注入 ApplicationScoped bean?

How to inject ApplicationScoped bean in Stateless bean?

我有调用异步操作的无状态 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 的处理方法绑定到一个按钮。 我想从处理器内部修改 ProcessHandler bean 的状态,这样我就可以向用户显示更新后的状态。

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

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


添加注入处理器时 class...

@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.

您应该从不在您的服务层 (EJB) 中包含任何特定于客户端的工件(JSF、JAX-RS、JSP/Servlet 等)。它使服务层在不同 clients/front-ends.

之间不可重用

只需将 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 上仅出于显而易见的原因。