当访问注入(inject)的服务时,如下所示 test()
抛出 NullPointerException
。
如果我不注入(inject)而是使用 BugService
的新实例,则 NPE
将在下一步抛出:BugService
的 getItems( )
。
实际上,我发现很难理解 JEE6-Tutorial 的 CDI 部分,所以我想我错过了一些非常基本的东西。感谢您的帮助。
这是 Java 类:
package hoho.misc;
import java.io.Serializable;
import javax.inject.Inject;
import javax.inject.Named;
import hoho.service.BugService;
@Named
public class Printer implements Serializable {
private static final long serialVersionUID = 1L;
@Inject
BugService bs;
public static void main(String[] args) {
Printer lPrinter = new Printer();
System.out.println(lPrinter.test());
}
public String test(){
String result = bs.getItems().toString();
return result;
}
}
以及注入(inject)的服务:
package hoho.service;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import hoho.model.generated.Item;
/**
* Session Bean implementation class ItemService
*/
@Stateless
public class BugService {
/**
* Default constructor.
*/
public BugService() {
}
@PersistenceContext
EntityManager em;
@SuppressWarnings("unchecked")
public List<Item> getItems() {
return this.em.createQuery(
"SELECT i FROM Item i")
.getResultList();
}
}
我的jboss-deployment-struct.xml
<jboss-deployment-structure xmlns="urn:jboss:deployment-structure:1.0">
<deployment>
<exclusions>
<module name="org.jboss.resteasy.resteasy-atom-provider" />
<module name="org.jboss.resteasy.resteasy-cdi" />
<module name="org.jboss.resteasy.resteasy-jaxrs" />
<module name="org.jboss.resteasy.resteasy-jaxb-provider" />
<module name="org.jboss.resteasy.resteasy-jackson-provider" />
<module name="org.jboss.resteasy.resteasy-jsapi" />
<module name="org.jboss.resteasy.resteasy-multipart-provider" />
<module name="org.jboss.resteasy.async-http-servlet-30" />
<module name="org.apache.log4j" />
</exclusions>
</deployment>
</jboss-deployment-structure>
<!--
<jboss-deployment-structure xmlns="urn:jboss:deployment-structure:1.0">
<deployment>
<exclusions>
<module name="org.jboss.as.jaxrs"/>
</exclusions>
</deployment>
</jboss-deployment-structure>
-->
这是我的 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://docs.jboss.org/cdi/beans_1_0.xsd">
</beans>
最佳答案
除非 JBOSS 中的某些内容与我使用的 java-ee 容器(glassfish)完全不同,否则您不应该尝试使用自制的主方法访问 bean(因为容器不会运行)。
一种选择是将命名 bean 绑定(bind)到某个 jsf 页面,并可能使用按钮调用 test()。
<h:form>
<h:commandButton action="#{printer.test}" value="Add"/>
</h:form>
关于mysql - 注入(inject)的服务不断抛出 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15731181/