我用一个无状态的Ejb编写了非常简单的Web应用程序,当我实现接口时,有趣的时刻来了 - ejb依赖注入不起作用:
的web.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类
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);
}
}
豆
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();
}
所以当我解开“implements Simple”时,我得到了NullPointerException(在接口中有@Remote或@Local注释),另一个案例我得到了“axaxaxa!”。为什么会这样?我读了Ejb类必须实现接口。
我使用的是TommEEcas Application Server。
答案 0 :(得分:5)
通过更改bean变量类型(到接口类型而不是类类型)来解决问题
具有NullPointerException的版本
private SimpleBean bean;
工作版
private Simple bean;
答案 1 :(得分:-1)
在排除故障之前,只需尝试重新启动容器(例如GlassFish,JBoss等)。