一、先给两个session Bean:
@Stateless(mappedName="helloBean")
@Remote(HelloWord.class)
①public class HelloWordBean implements HelloWord {
public String sayHello(String str) {
return str+"您好,这个表示测试成功,";
}
@Remote(LifeCycle.class)
@Stateless(mappedName="lifeCycleBean")
②public class LifeCycleBean implements LifeCycle {
@Override
public String sayBegin(String name) {
try{
Thread.sleep(1000*5);
}catch(InterruptedException e){
e.printStackTrace();
}
return "session bean 生命周期例子";
}
@Init
public void init(){
System.out.println("@Init事件触发");
}
@PostConstruct
public void construct(){
System.out.println("@construct事件触发");
}
@PreDestroy
public void exit(){
System.out.println("@PreDestroy事件触发");
}
它们分别的两个接口我想大家都自己写的出来吧!
下面直接说EJB3.0的DI设置注入方式的四种方法:(情况如在HelloWordBean需要另外一个LifeCycleBean 实例 )
第一种:通过全局JNDI方式,坏处移植性差。在HelloWordBean类里通过如下方式得到另外的bean实例:
InitialContext incx = new InitialContext();
LifeCycle lc = (LifeCycle)incx.lookup("lifeCycleBean#"+LifeCycle.class.getName());//返回lc实例
第二种:通过在在HelloWordBean类的成员属性或者字段使用EJB3.0的新注释@EJB
@EJB(mappedName="lifeCycleBean") LifeCycle lc;//返回lc实例
第三种:通过注册ENC方式(@注释方式、ejb-jar.xml、web.xml三种):应用服务器中的EJB容器有一个属于自己的的内部注册表,被称为ENC(enterprise Naming Context),EJB容器可以在其中维护某些指向外部资源的引用,把它想象成通讯薄,先要登记资源,在从中获取ENC资源的引用。
1.注释方式@
@EJB(name="ejb/lifeCycleBean",beanName="LifeCycleBean",beanInterface=LifeCycle.class)
获取另外bean实例:
InitialContext incx = new InitialContext();
LifeCycle lc = (LifeCycle)incx.lookup("java:comp/env/ejb/lifeCycleBean");//返回lc实例
2.配置符文件方式ejb-jar.xml
<enterprise-beans>
<session>
<ejb-name>HelloWordBean</ejb-name>
<ejb-ref>
<ejb-ref-name>ejb/lifeCycleBean</ejb-ref-name>
<ejb-ref-type>Session</ejb-ref-type>
<remote> com.bsm.test.statelessbean.LifeCycle</remote>
<ejb-link>LifeCycleBean</ejb-link>
</ejb-ref>
</session>
</enterprise-beans>
</ejb-jar>
二、客户端调用程序:
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8" import="java.util.*"%>
<%@ page import="javax.ejb.*"%>
<%@ page
import="javax.naming.*,
com.bsm.test.statelessbean.*,
com.bsm.test.stateful.*,"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>ejb3.0测试页面</title>
</head>
<body>
<%
Properties pro = new Properties();
pro.setProperty(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
pro.setProperty(Context.PROVIDER_URL, "t3://localhost:7001");
InitialContext context = new InitialContext(pro);
HelloWord hello = (HelloWord) context.lookup("helloBean#"+HelloWord.class.getName());
String str = hello.sayHello("ejb3.0");
System.out.println(str);
%>
</body>
</html>
Finally:success