您的位置:首页 > 其它

在Ejb3会话bean中调用其他Ejb3会话bean

2010-08-17 19:03 357 查看
SayMeRemote

package test2.sessionbean.dao;

import javax.naming.NamingException;

public interface SayMeRemote {
public String sayMe() throws NamingException;

public String sayMe2() throws NamingException;
}


SayMeBean

package test2.sessionbean.impl;

import javax.ejb.EJB;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import test1.sessionbean.dao.HelloWordRemote;
import test2.sessionbean.dao.SayMeRemote;

//@Stateless(name = "SayMeBean") 可以修改jndi的名称
@Stateless(name = "SayMeBean")
@Remote(SayMeRemote.class)
public class SayMeBean implements SayMeRemote {
// 在Ejb中调用其他的Ejb
// 方法1:使用jndi查找
public String sayMe() throws NamingException {
InitialContext ctx = new InitialContext();
HelloWordRemote helloWordRemote = (HelloWordRemote) ctx.lookup("HelloWordBean/remote");
String str = helloWordRemote.sayHello("张胜鸿");
return str;
}

// 方法2:使用Ejb注入
// @EJB 直接这样就可以,但是在实际中可以能有多个实现。
// 所以这样@EJB(beanName = "HelloWordBean") 可以具体指定。
@EJB(beanName = "HelloWordBean")
private HelloWordRemote helloWordRemote;

public String sayMe2() throws NamingException {
return helloWordRemote.sayHello("张胜鸿2");
}
}


Client

package test2.sessionbean.client;

import javax.naming.InitialContext;
import javax.naming.NamingException;

import test2.sessionbean.dao.SayMeRemote;

public class Client {
public static void main(String[] args) throws NamingException {
InitialContext ctx = new InitialContext();
SayMeRemote sayMeRemote = (SayMeRemote) ctx.lookup("SayMeBean/remote");
System.out.println(sayMeRemote.sayMe());
System.out.println(sayMeRemote.sayMe2());
}
}


补充:这个例子中ejb实现类调的类(HelloWordRemote )是在“用ejb3.0做的HelloWord!”这篇文章那个中的ejb。

其实就是在这里ejb中分别用两种不同的形式去调其他ejb中的一个方法,而那个方法return一个String。就这样,so easy!!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: