情景:有两个bean,一个是HelloWorldBean,一个是OtherBean,我们需要在HelloWorldBean的业务方法中调用OtherBean的业务方法,如何实现呢?
other接口
package cn.com.xinli.ejb3;
public interface Other
{
public String sayMe(String name);
}
接口实现
package cn.com.xinli.ejb3.impl;
import javax.ejb.Stateless;
import cn.com.xinli.ejb3.Other;
/*不写接口的类型则默认是本地接口*/
@Stateless
public class OtherBean implements Other
{
public String sayMe(String name)
{
return name+"也是一个bean";
}
}
在一个bean中引用其他bean 的服务,有两种实现方式:
一.使用jndi查找
二.使用注解
注意:
1.Ejb注解只能注入ejb,数据源呀,定时器呀需要Resources注解
2.如果有两个以上的ejb实现了一个接口,需要显示的写name 属性
package cn.com.xinli.ejb3.impl;
import javax.activation.DataSource;
import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateful;
import javax.ejb.TimerService;
import cn.com.xinli.ejb3.HelloWorld;
import cn.com.xinli.ejb3.HelloWorldLocal;
import cn.com.xinli.ejb3.Other;
/*表明这个ejb是有状态的会话bean*/
@Stateful
/*声明这个ejb的远程接口是HelloWorld,必须要写这个注解,否则调用的时候会报错*/
/*声明这个ejb的本地接口是HelloWorldLocal,必须要写这个注解,否则调用的时候会报错*/
@Local(HelloWorldLocal.class)
@Remote(HelloWorld.class)
public class HelloWorldBean implements HelloWorld,HelloWorldLocal
{
/*如果other接口被两个以上的ejb实现了,那么我们就必须使用@EJB的 name
* 属性,不然ejb容器不知道我们到底需要注入哪个ejb,则会抛一个例外
* 注入bean的名称为bean的简单名称,也就是不包含包名的简单类名
* */
@EJB(name="OtherBean") Other other;
//@EJB Other other;
/*注入定时器*/
//@Resource TimerService timerService;
/*注入数据源*/
//@Resource (mappedName="java:xxx") DataSource dataSource;
public String sayHello(String name)
{
//方式一
/*
try
{
InitialContext ctx=new InitialContext();
Other other=(Other)ctx.lookup("OtherBean/local");
return name+",你好,世界!我的ejb3的第一个例子!"+other.sayMe("ryp");
} catch (NamingException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
*/
//方式二
return name+",你好,世界!我的ejb3的第一个例子!"+other.sayMe("ryp");
}
}
编译->打包->部署->运行->ok