问题
I'm new to EJB, and I'm trying to understand the diference between Stateless and Stateful bean, so I made a simple example to test them.
@Stateless
public class Service {
private int num;
public Service(){
}
public int getNum() {
return num;
}
public void setNum() {
this.num++;
}
}
@WebServlet("/Controller1")
public class Controller1 extends HttpServlet {
@EJB
private Service serv;
public Controller1() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
serv.setNum();
response.getWriter().println(serv.getNum());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
And the Stateful equivalent:
@Stateful
public class ServiceStateful implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private int num;
public ServiceStateful(){
}
public int getNum() {
return num;
}
public void setNum() {
this.num++;
}
}
@WebServlet("/Controller")
public class Controller extends HttpServlet {
private static final long serialVersionUID = 1L;
@EJB
private ServiceStateful serv;
public Controller() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
serv.setNum();
response.getWriter().println(serv.getNum());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
Both examples act exactly the same, which is surprising for me. Can someone please explain what is the deal here?
回答1:
You can use instance variables of a stateless session bean, but they're not guaranteed to be preserved across method calls. If both approaches behave the same, it simply means you're probably getting the same stateless session bean instance across method calls within the same session.
回答2:
Your first example returns the previously set number by chance only : the get method could have been invoked on a different bean instance. It just happened to use the same instance in this particular case, but you can't count on it.
The second one is guaranteed to return you the previously set number, provided another request doesn't call the set method before the get method is called. A stateful bean should not be injected into a servlet.
回答3:
You are not supposed to have member fields (aka state) in a stateless session bean. For a stateful session bean it's ok. That's the difference.
回答4:
A stateful bean maintain it initial state during the conversation with the client (on or many).
A Stateless bean state can be changed (it attributes) during the conversation with the client (doesn't affect other clients)
you can see the difference if you execute multiple times!!
来源:https://stackoverflow.com/questions/7946589/ejb-example-for-stateless-and-stateful-beans-difference