jboss - EJB no se inyecta en JAX-RS
cdi (2)
Veo algunos problemas, algunos de ellos pueden ser pistas falsas, así que creo que los mencionaré todos.
No incluya toda esta configuración resteasy en su web.xml
. Probablemente esté confundiendo el servidor de la aplicación si nada más. Debería tener una aplicación JAX-RS que se vea así:
@ApplicationPath("/customers")
public class RestApplication extends Application {
// nothing needed ...
}
y eso es todo lo que se necesita Elimine el oyente y el servlet resteasy de su configuración.
Estás usando un CDI 1.1 beans.xml
. EAP 6.2 cumple con CDI 1.0. Haga el archivo vacío o use una etiqueta CDI 1.0 en su archivo.
¿De hecho tiene dos clases diferentes de CustomerWS
? o fue un problema de copiar y pegar?
Estoy usando JBoss 6.2.0 EAP, estoy tratando de inyectar mi EJB en mis clases de JAX-RS, pero obtengo un NullPointerEXception. Definitivamente es la clase CUstomerDAO, porque el error en la línea 29 es el método printOut que se invoca en un objeto nulo. Agregué beans.xml a mi WEB-INF. Me pregunto si el servlet que agregué o la configuración web.xml que agregué me da un error. He declarado una fuente de datos en el servidor jboss y está funcionando bien. Es solo que las cosas nuevas que agregué parecen arrojar el error. Si alguien quiere el proyecto, puedo ponerlo.
Aquí están mis archivos
Error en el seguimiento de pila
10:11:32,834 INFO [org.jboss.as.server.deployment] (MSC service thread 1-2) JBAS015876: Starting deployment of "mysql-connector-java-5.1.29-bin.jar" (runtime-name: "mysql-connector-java-5.1.29-bin.jar")
10:11:32,835 INFO [org.jboss.as.server.deployment.scanner] (MSC service thread 1-4) JBAS015012: Started FileSystemDeploymentService for directory /opt/jboss-eap-6.2/standalone/deployments
10:11:33,508 INFO [org.jboss.as.connector.deployers.jdbc] (MSC service thread 1-1) JBAS010404: Deploying non-JDBC-compliant driver class com.mysql.jdbc.Driver (version 5.1)
10:11:33,536 INFO [org.jboss.as.connector.subsystems.datasources] (MSC service thread 1-4) JBAS010400: Bound data source [java:/tutorial]
10:11:33,769 INFO [org.jboss.as.server] (Controller Boot Thread) JBAS018559: Deployed "mysql-connector-java-5.1.29-bin.jar" (runtime-name : "mysql-connector-java-5.1.29-bin.jar")
10:11:33,852 INFO [org.jboss.as] (Controller Boot Thread) JBAS015961: Http management interface listening on http://127.0.0.1:9990/management
10:11:33,852 INFO [org.jboss.as] (Controller Boot Thread) JBAS015951: Admin console listening on http://127.0.0.1:9990
10:11:33,853 INFO [org.jboss.as] (Controller Boot Thread) JBAS015874: JBoss EAP 6.2.0.GA (AS 7.3.0.Final-redhat-14) started in 6615ms - Started 160 of 220 services (58 services are passive or on-demand)
10:12:44,006 INFO [org.jboss.as.repository] (HttpManagementService-threads - 2) JBAS014900: Content added at location /opt/jboss-eap-6.2/standalone/data/content/bc/c99f85aabe406819b2f1f6d5c660b3fcb0d231/content
10:12:51,778 INFO [org.jboss.as.server.deployment] (MSC service thread 1-4) JBAS015876: Starting deployment of "webproject.war" (runtime-name: "webproject.war")
10:12:52,031 WARN [org.jboss.weld.deployer] (MSC service thread 1-2) JBAS016010: Warning while parsing vfs:/content/webproject.war/WEB-INF/beans.xml:6 SchemaLocation: schemaLocation value = '' http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd'' must have even number of URI''s.
10:12:52,103 INFO [org.jboss.as.jpa] (MSC service thread 1-2) JBAS011401: Read persistence.xml for tutorial
10:12:52,239 INFO [org.jboss.weld.deployer] (MSC service thread 1-2) JBAS016002: Processing weld deployment webproject.war
10:12:52,267 INFO [org.jboss.as.ejb3.deployment.processors.EjbJndiBindingsDeploymentUnitProcessor] (MSC service thread 1-2) JNDI bindings for session bean named WebProject in deployment unit deployment "webproject.war" are as follows:
java:global/webproject/WebProject!com.example.ejbrest.WebProject
java:app/webproject/WebProject!com.example.ejbrest.WebProject
java:module/WebProject!com.example.ejbrest.WebProject
java:global/webproject/WebProject
java:app/webproject/WebProject
java:module/WebProject
10:12:52,268 INFO [org.jboss.as.ejb3.deployment.processors.EjbJndiBindingsDeploymentUnitProcessor] (MSC service thread 1-2) JNDI bindings for session bean named CustomerDAO in deployment unit deployment "webproject.war" are as follows:
java:global/webproject/CustomerDAO!com.example.ejbrest.CustomerDAO
java:app/webproject/CustomerDAO!com.example.ejbrest.CustomerDAO
java:module/CustomerDAO!com.example.ejbrest.CustomerDAO
java:global/webproject/CustomerDAO
java:app/webproject/CustomerDAO
java:module/CustomerDAO
10:12:52,270 INFO [org.jboss.as.ejb3.deployment.processors.EjbJndiBindingsDeploymentUnitProcessor] (MSC service thread 1-2) JNDI bindings for session bean named CustomerWS in deployment unit deployment "webproject.war" are as follows:
java:global/webproject/CustomerWS!com.example.ejbrest.CustomerWS
java:app/webproject/CustomerWS!com.example.ejbrest.CustomerWS
java:module/CustomerWS!com.example.ejbrest.CustomerWS
java:global/webproject/CustomerWS
java:app/webproject/CustomerWS
java:module/CustomerWS
10:12:52,514 INFO [org.jboss.weld.deployer] (MSC service thread 1-3) JBAS016005: Starting Services for CDI deployment: webproject.war
10:12:52,598 INFO [org.jboss.weld.Version] (MSC service thread 1-3) WELD-000900 1.1.16 (redhat)
10:12:52,657 INFO [org.jboss.weld.deployer] (MSC service thread 1-1) JBAS016008: Starting weld service for deployment webproject.war
10:12:52,658 INFO [org.jboss.as.jpa] (ServerService Thread Pool -- 48) JBAS011402: Starting Persistence Unit Service ''webproject.war#tutorial''
10:12:52,879 INFO [org.hibernate.annotations.common.Version] (ServerService Thread Pool -- 48) HCANN000001: Hibernate Commons Annotations {4.0.1.Final-redhat-2}
10:12:52,897 INFO [org.hibernate.Version] (ServerService Thread Pool -- 48) HHH000412: Hibernate Core {4.2.7.SP1-redhat-3}
10:12:52,900 INFO [org.hibernate.cfg.Environment] (ServerService Thread Pool -- 48) HHH000206: hibernate.properties not found
10:12:52,912 INFO [org.hibernate.cfg.Environment] (ServerService Thread Pool -- 48) HHH000021: Bytecode provider name : javassist
10:12:52,937 INFO [org.hibernate.ejb.Ejb3Configuration] (ServerService Thread Pool -- 48) HHH000204: Processing PersistenceUnitInfo [
name: tutorial
...]
10:12:53,042 INFO [org.hibernate.service.jdbc.connections.internal.ConnectionProviderInitiator] (ServerService Thread Pool -- 48) HHH000130: Instantiating explicit connection provider: org.hibernate.ejb.connection.InjectedDataSourceConnectionProvider
10:12:53,377 INFO [org.hibernate.dialect.Dialect] (ServerService Thread Pool -- 48) HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
10:12:53,496 INFO [org.hibernate.engine.transaction.internal.TransactionFactoryInitiator] (ServerService Thread Pool -- 48) HHH000268: Transaction strategy: org.hibernate.engine.transaction.internal.jta.CMTTransactionFactory
10:12:53,502 INFO [org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory] (ServerService Thread Pool -- 48) HHH000397: Using ASTQueryTranslatorFactory
10:12:53,563 INFO [org.hibernate.validator.internal.util.Version] (ServerService Thread Pool -- 48) HV000001: Hibernate Validator 4.3.1.Final-redhat-1
10:12:54,400 INFO [org.jboss.web] (ServerService Thread Pool -- 49) JBAS018210: Register web context: /webproject
10:12:54,476 INFO [org.jboss.resteasy.cdi.CdiInjectorFactory] (ServerService Thread Pool -- 49) Found BeanManager at java:comp/BeanManager
10:12:55,057 INFO [org.jboss.as.server] (HttpManagementService-threads - 2) JBAS018559: Deployed "webproject.war" (runtime-name : "webproject.war")
10:13:08,430 INFO [org.jboss.resteasy.plugins.server.servlet.ServletContainerDispatcher] (http-localhost/127.0.0.1:8080-1) Deploying javax.ws.rs.core.Application: class com.example.ejbrest.RestApplication$Proxy$_$$_WeldClientProxy
10:13:08,441 INFO [org.jboss.resteasy.plugins.server.servlet.ServletContainerDispatcher] (http-localhost/127.0.0.1:8080-1) Adding singleton resource com.example.ejbrest.CustomerWS from Application javax.ws.rs.core.Application
10:13:08,649 ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/webproject].[Resteasy]] (http-localhost/127.0.0.1:8080-1) JBWEB000236: Servlet.service() for servlet Resteasy threw exception: org.jboss.resteasy.spi.UnhandledException: java.lang.NullPointerException
at org.jboss.resteasy.core.SynchronousDispatcher.handleApplicationException(SynchronousDispatcher.java:365) [resteasy-jaxrs-2.3.7.Final-redhat-2.jar:2.3.7.Final-redhat-2]
at org.jboss.resteasy.core.SynchronousDispatcher.handleException(SynchronousDispatcher.java:233) [resteasy-jaxrs-2.3.7.Final-redhat-2.jar:2.3.7.Final-redhat-2]
at org.jboss.resteasy.core.SynchronousDispatcher.handleInvokerException(SynchronousDispatcher.java:209) [resteasy-jaxrs-2.3.7.Final-redhat-2.jar:2.3.7.Final-redhat-2]
at org.jboss.resteasy.core.SynchronousDispatcher.getResponse(SynchronousDispatcher.java:557) [resteasy-jaxrs-2.3.7.Final-redhat-2.jar:2.3.7.Final-redhat-2]
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:524) [resteasy-jaxrs-2.3.7.Final-redhat-2.jar:2.3.7.Final-redhat-2]
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:126) [resteasy-jaxrs-2.3.7.Final-redhat-2.jar:2.3.7.Final-redhat-2]
at org.jboss.resteasy.plugins.server.servlet.ServletContainerDispatcher.service(ServletContainerDispatcher.java:208) [resteasy-jaxrs-2.3.7.Final-redhat-2.jar:2.3.7.Final-redhat-2]
at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:55) [resteasy-jaxrs-2.3.7.Final-redhat-2.jar:2.3.7.Final-redhat-2]
at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:50) [resteasy-jaxrs-2.3.7.Final-redhat-2.jar:2.3.7.Final-redhat-2]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:847) [jboss-servlet-api_3.0_spec-1.0.2.Final-redhat-1.jar:1.0.2.Final-redhat-1]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:295) [jbossweb-7.2.2.Final-redhat-1.jar:7.2.2.Final-redhat-1]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214) [jbossweb-7.2.2.Final-redhat-1.jar:7.2.2.Final-redhat-1]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230) [jbossweb-7.2.2.Final-redhat-1.jar:7.2.2.Final-redhat-1]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:149) [jbossweb-7.2.2.Final-redhat-1.jar:7.2.2.Final-redhat-1]
at org.jboss.as.jpa.interceptor.WebNonTxEmCloserValve.invoke(WebNonTxEmCloserValve.java:50) [jboss-as-jpa-7.3.0.Final-redhat-14.jar:7.3.0.Final-redhat-14]
at org.jboss.as.jpa.interceptor.WebNonTxEmCloserValve.invoke(WebNonTxEmCloserValve.java:50) [jboss-as-jpa-7.3.0.Final-redhat-14.jar:7.3.0.Final-redhat-14]
at org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:169) [jboss-as-web-7.3.0.Final-redhat-14.jar:7.3.0.Final-redhat-14]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:145) [jbossweb-7.2.2.Final-redhat-1.jar:7.2.2.Final-redhat-1]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:97) [jbossweb-7.2.2.Final-redhat-1.jar:7.2.2.Final-redhat-1]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:102) [jbossweb-7.2.2.Final-redhat-1.jar:7.2.2.Final-redhat-1]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:336) [jbossweb-7.2.2.Final-redhat-1.jar:7.2.2.Final-redhat-1]
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:856) [jbossweb-7.2.2.Final-redhat-1.jar:7.2.2.Final-redhat-1]
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:653) [jbossweb-7.2.2.Final-redhat-1.jar:7.2.2.Final-redhat-1]
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:920) [jbossweb-7.2.2.Final-redhat-1.jar:7.2.2.Final-redhat-1]
at java.lang.Thread.run(Thread.java:744) [rt.jar:1.7.0_51]
Caused by: java.lang.NullPointerException
at com.example.ejbrest.CustomerWS.getCustomer(CustomerWS.java:29) [classes:]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.7.0_51]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) [rt.jar:1.7.0_51]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [rt.jar:1.7.0_51]
at java.lang.reflect.Method.invoke(Method.java:606) [rt.jar:1.7.0_51]
at org.jboss.resteasy.core.MethodInjectorImpl.invoke(MethodInjectorImpl.java:167) [resteasy-jaxrs-2.3.7.Final-redhat-2.jar:2.3.7.Final-redhat-2]
at org.jboss.resteasy.core.ResourceMethod.invokeOnTarget(ResourceMethod.java:269) [resteasy-jaxrs-2.3.7.Final-redhat-2.jar:2.3.7.Final-redhat-2]
at org.jboss.resteasy.core.ResourceMethod.invoke(ResourceMethod.java:227) [resteasy-jaxrs-2.3.7.Final-redhat-2.jar:2.3.7.Final-redhat-2]
at org.jboss.resteasy.core.ResourceMethod.invoke(ResourceMethod.java:216) [resteasy-jaxrs-2.3.7.Final-redhat-2.jar:2.3.7.Final-redhat-2]
at org.jboss.resteasy.core.SynchronousDispatcher.getResponse(SynchronousDispatcher.java:542) [resteasy-jaxrs-2.3.7.Final-redhat-2.jar:2.3.7.Final-redhat-2]
... 21 more
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<display-name>RestEasy sample Web Application</display-name>
<listener>
<listener-class>
org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap
</listener-class>
</listener>
<servlet>
<servlet-name>Resteasy</servlet-name>
<servlet-class>
org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.example.ejbrest.RestApplication</param-value>
</init-param>
<!-- <load-on-startup>1</load-on-startup>-->
</servlet>
<servlet-mapping>
<servlet-name>Resteasy</servlet-name>
<url-pattern>/customers/*</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>ControllerServlet</servlet-name>
<servlet-class>com.example.ejbrest.ControllerServlet</servlet-class>
<!-- <load-on-startup>0</load-on-startup>-->
</servlet>
<servlet-mapping>
<servlet-name>ControllerServlet</servlet-name>
<!-- <url-pattern>/tutorial/*</url-pattern>-->
<url-pattern>/application/*</url-pattern>
</servlet-mapping>
</web-app>
beans.xml
<!-- Marker file indicating CDI should be enabled -->
<beans xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd">
</beans>
<!-- http://java.sun.com/xml/ns/javaee/beans_1_0.xsd"
http://java.sun.com/xml/ns/javaee -->
persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
version="1.0">
<persistence-unit name="tutorial">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:/tutorial</jta-data-source>
<properties>
<property name="hibernate.archive.autodetection" value="class" />
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
<property name="hibernate.show_sql" value="true" />
</properties>
</persistence-unit>
</persistence>
Clases de Java:
package com.example.ejbrest;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import org.jboss.resteasy.plugins.providers.html.View;
@Path("/customers")
@Stateless
@LocalBean
public class CustomerWS {
@EJB
private CustomerDAO customersDao;
@GET
@Path("/first/{id}")
public Customer getCustomer(@PathParam("id") int id) {
customersDao.printOut();
return customersDao.getCustomer(id);
}
@GET
@Path("/second/{id}")
public View getCustomer() {
System.out.println("Got in here! ! ! ");
View v = new View("/application");
//v.render(arg0, arg1);
//System.out.println("path " + v.getPath());
return v;
}
@POST
public void addCustomers(List<Customer> customers) {
customersDao.addCustomers(customers);
}
}
CustomerDAO:
package com.example.ejbrest;
import java.util.List;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
@Stateless
@LocalBean
public class CustomerDAO {
@PersistenceContext
private EntityManager em;
public Customer getCustomer(int id) {
return em.find(Customer.class, id);
}
public void printOut(){
System.out.println("AGGGGGH!");
}
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void addCustomers(List<Customer> customers) {
for (Customer customer : customers) {
em.persist(customer);
}
}
}
ClienteWS
package com.example.ejbrest;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import org.jboss.resteasy.plugins.providers.html.View;
@Path("/customers")
@Stateless
@LocalBean
public class CustomerWS {
@EJB
private CustomerDAO customersDao;
@GET
@Path("/first/{id}")
public Customer getCustomer(@PathParam("id") int id) {
customersDao.printOut();
return customersDao.getCustomer(id);
}
@GET
@Path("/second/{id}")
public View getCustomer() {
System.out.println("Got in here! ! ! ");
View v = new View("/application");
//v.render(arg0, arg1);
//System.out.println("path " + v.getPath());
return v;
}
@POST
public void addCustomers(List<Customer> customers) {
customersDao.addCustomers(customers);
}
}
Estructura de directorios
En primer lugar, varias notas para su código:
- no necesita el archivo beans.xml en el proyecto porque use no use anotaciones CDI sino solo anotaciones EJB3
- No se requiere la anotación @LocalBean, @Stateless es suficiente para definir el bean local, se puede encontrar una explicación detallada en EJB 3.1 @LocalBean sin anotación
- no es necesaria la definición de los elementos listener, servlet y servlet-mapping para resteasy en web.xml, JBoss / RestEasy (biblioteca de implementación JAX-RS) agrega estas definiciones automáticamente. Vaciar web.xml con elemento raíz de la aplicación web es suficiente.
Ahora a su problema: El contenedor EJB no inyecta el atributo CustomerWS.customersDao porque CustomerWS no se despliega como bean EJB por contenedor, sino solo como recurso JAX-RS por RestEasy. Es un inconveniente conocido de RestEasy 2.x utilizado en JBoss EAP 6.x, ese recurso restfull no podría convertirse en un bean EJB de la caja: https://docs.jboss.org/resteasy/docs/2.3.6.Final/userguide /html/RESTEasy_EJB_Integration.html
Todo lo que necesita hacer es definir un parámetro de contexto especial en web.xml con nombres jndi separados por comas de beans EJB que también son recursos restfull administrados por RestEasy. Entonces, en su caso, debe insertar en web.xml el siguiente fragmento de código:
<context-param>
<param-name>resteasy.jndi.resources</param-name>
<param-value>java:module/CustomerWS</param-value>
</context-param>
Y eso es todo. Ahora la clase CustomerWS se manejará como bean EJB con inyecciones de trabajo.