如何创建按需实例?

Tho*_*usD 4 java asynchronous servlets java-ee cdi

在调用必须将新实例作为参数传递的Java方法时,如何通过CDI容器创建此新实例?

在以下示例中:我正在向异步servlet上下文添加侦听器:

@WebServlet(value = "/example", asyncSupported = true)
public class ExampleServlet extends HttpServlet {

    @Override
    protected void doPost(final HttpServletRequest req,
        final HttpServletResponse resp) throws ServletException,
        IOException {

        // ... some code

        AsyncContext aCtx = req.startAsync(req, resp);
        aCtx.addListener(**new AsyncListener()** {
             // implementation of the async listener
        });
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)

因此,我希望它不是手动执行这个新的AsyncListener()实例化,而是由CDI容器创建.

当然,我希望每个aync上下文都有自己的侦听器实例,否则我只是将@Inject注入一个AsyncListener作为servlet类的一个字段.

目前,找不到任何办法.有人有想法分享?

Tom*_*son 5

注入Instance你的听众.如果侦听器类在依赖范围内,则每次调用都get()将产生一个新实例.

@Inject
private Instance<MyAsyncListener> listenerFactory;
Run Code Online (Sandbox Code Playgroud)

和:

    aCtx.addListener(listenerFactory.get());
Run Code Online (Sandbox Code Playgroud)

我已经调用了变量,listenerFactory因为这就是它在这里使用的方式.

我在JBoss AS7.1.1上进行了测试,它使用Weld 1.1.5作为其CDI提供程序,但我认为这是标准行为.