@Inject 在 JAX-RS 资源中不起作用

@Inject is not working in JAX-RS resource

我正在尝试将 @Inject 与 JAX-RS 结合使用。我的问题是@Inject 只在Servlet 中工作。在 JAX-RS 资源中,我得到了空指针,我不知道我做错了什么。我的代码如下所示:

Pom.xml

<dependencies>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.16.8</version>
    </dependency>

    <dependency>
        <!-- JBoss/Weld Refrence Implementation for CDI on a Servlet Container -->
        <groupId>org.jboss.weld.servlet</groupId>
        <artifactId>weld-servlet</artifactId>
        <version>2.3.4.Final</version>
        <scope>runtime</scope>
    </dependency>

    <dependency>
        <groupId>javax.enterprise</groupId>
        <artifactId>cdi-api</artifactId>
        <version>1.2</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <!-- Provided by Tomcat, but needed for compilation -->
        <groupId>javax</groupId>
        <artifactId>javaee-web-api</artifactId>
        <version>7.0</version>
        <scope>provided</scope>
    </dependency>

    <!-- Twitter API -->
    <dependency>
        <groupId>org.twitter4j</groupId>
        <artifactId>twitter4j-core</artifactId>
        <version>4.0.4</version>
    </dependency>

    <dependency>
        <groupId>org.twitter4j</groupId>
        <artifactId>twitter4j-stream</artifactId>
        <version>4.0.4</version>
    </dependency>

    <!-- Logging -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.21</version>
    </dependency>

    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
        <version>1.1.7</version>
    </dependency>

    <!-- Tests -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>3.8.1</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-server</artifactId>
        <version>1.9</version>
    </dependency>

</dependencies>

Beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
  http://java.sun.com/xml/ns/javaee 
  http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
</beans>`

web.xml 包含:

<resource-env-ref> <!-- Enable Weld CDI, also needs META-INF/context.xml entry --> <resource-env-ref-name>BeanManager</resource-env-ref-name> <resource-env-ref-type>javax.enterprise.inject.spi.BeanManager</resource-env-ref-type> </resource-env-ref>

工作class:

package com.tinf15B2.webengeneering.boundary;

import javax.inject.Inject;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;

import com.tinf15B2.webengeneering.facade.Control;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class StartUpService implements ServletContextListener {

@Inject
private Control serviceController;

@Override
public void contextDestroyed(ServletContextEvent arg0) {
    serviceController.stopTweetListener();
    log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Service was closed");
}

@Override
public void contextInitialized(ServletContextEvent arg0) {
    serviceController.startTweetListener();
    log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Service started");
}
}

serviceController.startTweetListener() 和 serviceController.stopTweetListener() 有效。没有空指针。

不工作class:

import java.util.Date;

import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import com.tinf15B2.webengeneering.facade.Control;

@Path("/")
public class HashTagStatistic {

    @Inject
    private Control serviceController;

    @GET
    @Produces("text/html")
    public Response getStartingPage()
    {
        String output = "<h1>Hello World!<h1>" +
                "<p>RESTful Service is running ... <br>Ping @ " + new Date().toString() + "</p<br>";
        return Response.status(200).entity(output).build();
    }   

    @Path("resources/hashtagstatistic")
    @GET
    @Produces("text/html")
    public Response getHashTagStatisticAsHtml(){
        return Response //
                .status(200) //
                .entity(serviceController.getDatabaseContent()) //
                .build();
    }
}

但是当我尝试在此 class 中调用 serviceController.getDatabaseContent() 时,我得到一个空指针。

错误日志:

java.lang.NullPointerException
    com.tinf15B2.webengeneering.boundary.HashTagStatistic.getHashTagStatisticAsHtml(HashTagStatistic.java:33)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    java.lang.reflect.Method.invoke(Unknown Source)
    com.sun.jersey.spi.container.JavaMethodInvokerFactory.invoke(JavaMethodInvokerFactory.java:60)
    com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$ResponseOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:205)
    com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
    com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:288)
    com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
    com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
    com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
    com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
    com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1469)
    com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1400)
    com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1349)
    com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1339)
    com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
    com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)
    com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:699)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

我不知道出了什么问题。如果有人有解决方案就太棒了 =)

谢谢!

您的 HashTagStatistic 是一个 JAX-RS 资源。 JAX-RS 资源有自己的生命周期,由 JAX-RS 实现本身处理,CDI 不是这个生命周期的一部分。但是,许多 JAX-RS 实现提供了一个您可以启用的 CDI/JAX-RS 桥。

您似乎正在使用 Jersey 1 作为 JAX-RS 实现,因此这应该对您有所帮助:

如果您正在考虑升级到 Jersey 2,请阅读此文档:https://jersey.java.net/documentation/latest/cdi.support.html