How to create instances on demand?

When calling a Java method on which you must pass a new instance as a parameter, how is it possible that this new instance is created by the CDI container?

In the following example: I add a listener to the asynchronous servlet context:

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

So instead of manually executing this new AsyncListener () creation, I would like it to be created by the CDI container.

Of course, I want each aync context to have its own listener instance, otherwise I would just inject AsyncListener with @Inject as a field in the servlet class.

At the moment, no way has been found to do this. Does anyone have an idea to share?

+4
source share
2 answers

Add Instance your listener. If the listener class is in a dependent scope, then each call to get() will give a new instance.

 @Inject private Instance<MyAsyncListener> listenerFactory; 

and

  aCtx.addListener(listenerFactory.get()); 

I named the variable listenerFactory because it is used here.

I tested this on JBoss AS7.1.1, which uses Weld 1.1.5 as its CDI provider, but I think this is standard behavior.

+5
source

Bean injection points are processed when the bean is created, so unfortunately you cannot explicitly call an injection. This may (and hopefully will) change in later releases of CDI.

One approach that I know of can be used in some cases to get around this limitation, to encapsulate or get the class that you want to implement by providing it with an injection field or an initialization method. In this case, it will be AsyncContext , but you cannot control what the HttpServletRequest will return, so this parameter is not applicable here.

Maybe you could do something with the CDI BeanManager - but I'm afraid it will take a lot more effort than calling new

0
source

Source: https://habr.com/ru/post/1445944/


All Articles