Я пытаюсь использовать @Inject с JAX-RS. Моя проблема в том, что @Inject работает только в Servlets. В ресурсах JAX-RS я получаю nullpointer, и я понятия не имею, что я делаю неправильно. Мой код выглядит следующим образом:@Inject не работает в ресурсе 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>
рабочий класс:
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() работают. Нет нулевого указателя.
не работает класс:
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();
}
}
Но когда я пытаюсь вызвать serviceController.getDatabaseContent() в этом классе я получаю NullPointer.
Ошибка-Log:
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$1.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)
У меня нет idead, что это неправильно. Было бы здорово, если бы у кого-нибудь было решение =)
Спасибо!
@BalusC Вы отметили это как дубликат вопроса Jersey2 (groupId 'org.glassfish.jersey), однако оригинальный плакат использует Jersey1 (groupId' com.sun.jersey'). Лучшая ссылка была бы такой: http://stackoverflow.com/q/22994058/2492865 –