java EJB注入时空指针异常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16056881/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Null pointer exception while EJB injection
提问by Cherry
I wrote very simple web application with one stateless Ejb, the interesting moment comes when I implement interface - ejb dependency injection does not work:
我用一个无状态 Ejb 编写了非常简单的 Web 应用程序,当我实现接口时,有趣的时刻来了 - ejb 依赖注入不起作用:
web.xml
网页.xml
<?xml version="1.0" ?>
<web-app 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/web-app_3_0.xsd"
version="3.0">
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>simpleController</servlet-name>
<servlet-class>com.SimpleController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>simpleController</servlet-name>
<url-pattern>*.job</url-pattern>
</servlet-mapping>
</web-app>
Servlet class
小服务程序类
package com;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class SimpleController extends HttpServlet {
@EJB
private SimpleBean bean;
@Override
protected void doPost (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().println(bean.getSomeString());
}
@Override
protected void doGet (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
}
bean
豆角,扁豆
package com;
import javax.ejb.Stateless;
@Stateless
public class SimpleBean /*implements Simple*/ {
public String getSomeString(){
return "axaxaxa!";
}
}
inteface
界面
package com;
import javax.ejb.Remote;
//@Local
@Remote
public interface Simple {
String getSomeString();
}
So when I uncoment "implements Simple" I got NullPointerException (with @Remote or @Local annotation in interface), another case I get "axaxaxa!". Why it happens? I read the Ejb class mustimplement intefaces.
因此,当我取消注释“implements Simple”时,我得到了 NullPointerException(界面中带有 @Remote 或 @Local 注释),另一种情况我得到了“axaxaxa!”。为什么会发生?我读过 Ejb 类必须实现接口。
I use TommEEcas Application Server.
我使用 TommEEcas 应用程序服务器。
回答by Cherry
Problem solves by changing bean variable type (to interface type instead of class type)
通过改变bean变量类型解决问题(改为接口类型而不是类类型)
Version with NullPointerException
带有 NullPointerException 的版本
private SimpleBean bean;
Working version
工作版本
private Simple bean;
回答by Philip Durbin
Before you troubleshoot too much, simply try restarting your container (i.e. GlassFish, JBoss, etc.).
在进行过多故障排除之前,只需尝试重新启动容器(即 GlassFish、JBoss 等)。