当访问如下注入的服务时,test()
会抛出一个NullPointerException
.
如果我不注入但使用新实例,BugService
将NPE
在下一步抛出:BugService
's 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;
}
}
和注入的服务:
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-structure.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>