gpt4 book ai didi

java - 无状态和有状态 bean 区别的 EJB 示例

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:41:59 25 4
gpt4 key购买 nike

<分区>

我是 EJB 的新手,我想了解无状态 bean 和有状态 bean 之间的区别,所以我做了一个简单的例子来测试它们。

@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 {

}

}

和有状态的等价物:

@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 {

}

}

两个例子的行为完全一样,这让我很惊讶。有人可以解释一下这是怎么回事吗?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com