Weld CDI on Google App Engine: Injection in servle

2019-07-19 07:30发布

This is my first time working with GAE and I'm trying to get CDI working. Long story short: The @Inject field in my servlet is not getting injected (it's always null).

I'm working in Eclipse and debug the application on the local test server included in the GAE SDK (which is started by Eclipse as well). When I access the servlet on localhost, I get a null-pointer exception for someService. I've also output the value of someService to verify it is really null, which it is.

Edit: When I added a @Named("skldjfx") qualifier to the injection point, Weld complained the dependency is unsatisfied (in the validation phase), so that's a good sign. However, the field is still always null.

Servlet:

public class BlogServlet extends HttpServlet {

    @Inject private SomeService someService;

    public void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws IOException {

        resp.setContentType("text/plain");
        resp.getWriter().println("Hello. " + someService.getSomeValue());
        //                                      \
        //                                  always null
    }
}

SomeService class:

@ApplicationScoped
public class SomeService {

    private String someValue = "some value";

    public String getSomeValue() {
        return someValue;
    }
}

I've configured Weld's Listener in web.xml:

<listener>
    <listener-class>org.jboss.weld.environment.servlet.Listener</listener-class>
</listener>

The listener is properly loaded because it logs its initialization message: org.jboss.weld.environment.servlet.Listener contextInitialized.

I've included (an empty) beans.xml in both war/WEB-INF and war/META-INF. I also tried it without META-INF. Maybe beans.xml isn't processed? Other contents in the WEB-INF folder (such as web.xml) are processed properly.

How can I verify if beans.xml is processed and/or fix SomeService not getting injected?

1条回答
我只想做你的唯一
2楼-- · 2019-07-19 07:51

It looks like it's not possible to use CDI with GAE, because GAE's Jetty fork ignores jetty-web.xml, which is needed to specify the BeanManager. See this link and this link. Really strange GAE is not supporting the use of CDI.

Note that these links are really old, but so far I haven't found any evidence to the contrary.

Anyway, my next step will be to use Google's own dependency injection framework Guice. Using it with GAE is described here. I'd prefer CDI though.

查看更多
登录 后发表回答