② EJB有状态的bean
程序员文章站
2022-03-11 08:59:52
...
② EJB有状态的bean
1.定义
有状态会话bean是一种企业bean的它与客户保持会话状态。有状态会话Bean根据其名声在它的实例变量相关的客户端状态。 EJB容器创建一个单独的有状态会话bean来处理客户端的每个请求。只要请求范围已经结束,statelful会话bean被销毁。类似于spring中的多例或者session会话域。
2.注意事项
2.1 服务端注意事项(EJBServerStateFul)
需要加上@Stateful注解,表示该类为有状态的bean
@Stateful
@Remote
public class LibraryStatefulSessionBean implements LibraryStatefulSessionBeanRemote {
2.2 客户端注意事项(EJBClientStateFul)
我们在进行远程调用的时候,一定要加上我们的状态,否则会报错,找不到状态,因为是有状态的bean在提供服务,所以我们的状态就显得格外的重要了。(具体如何加状态,见文章1)
libraryStatefulSessionBeanRemote = (LibraryStatefulSessionBeanRemote) context.lookup("ejb:/EJBServerStateFul_war_exploded/LibraryStatefulSessionBean!pers.jhl.session.stateless.LibraryStatefulSessionBeanRemote?stateful=TMingYi");
3.完整代码
(基础的集合存书)
3.1 服务端
LibraryStatefulSessionBeanRemote:
public interface LibraryStatefulSessionBeanRemote {
void addBook(String bookName);
List getBooks();
}
LibraryStatefulSessionBean:
//表示有状态的EJB,每一个请求打过来,都会产生一个新的对象
@Stateful
@Remote
public class LibraryStatefulSessionBean implements LibraryStatefulSessionBeanRemote {
List<String> bookShelf;
public LibraryStatefulSessionBean(){
bookShelf = new ArrayList<String>();
}
public void addBook(String bookName) {
bookShelf.add(bookName);
}
public List<String> getBooks() {
return bookShelf;
}
}
3.2 客户端
LibraryStatefulSessionBeanRemote:
public interface LibraryStatefulSessionBeanRemote {
void addBook(String bookName);
List getBooks();
}
EJBTester(主方法):
import java.awt.print.Book;
import java.io.*;
import java.util.List;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class EJBTester {
static LibraryStatefulSessionBeanRemote libraryStatefulSessionBeanRemote;
static {
try{
Properties pro = new Properties();
pro.put(Context.URL_PKG_PREFIXES,"org.jboss.ejb.client.naming");
pro.put("jboss.naming.client.ejb.context",true);
Context context = new InitialContext(pro);
libraryStatefulSessionBeanRemote = (LibraryStatefulSessionBeanRemote) context.lookup("ejb:/EJBServerStateFul_war_exploded/LibraryStatefulSessionBean!pers.jhl.session.stateless.LibraryStatefulSessionBeanRemote?stateful=TMingYi");
}catch(NamingException e){
e.printStackTrace();
}
}
public static void main(String[] args) {
List<String> books = libraryStatefulSessionBeanRemote.getBooks();
for (String book : books) {
System.out.println(book);
}
}
}
上一篇: EJB--应用创造下
下一篇: EJB3开发第一个无状态会话bean
推荐阅读
-
Spring的并发问题——有状态Bean和无状态Bean
-
芒果的储存方法有哪些?不同状态的芒果储存方法大不相同
-
利用mapWithState实现按照首字母统计的有状态的wordCount
-
Apache Flink 概览 - 有状态的流式计算
-
Apache Flink 概览 - 有状态的流式计算
-
spring 中属性scope 的prototype(有状态)和singleton(无状态)
-
我的电脑中磁盘管理显示状态良好(有危险)的解决方案
-
有状态的WEB应用
-
PHP有相仿WebBrowser的事件判断么,比如加载完成事件,当前加载状态等
-
bean、pojo、model、entity、EJB的区别