`
tigers20010
  • 浏览: 47260 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

通过注解方式注入并使用其他EJB或者服务(八).doc

EJB 
阅读更多

 

 

 

在一个项目中EJB的数量可以有很多,EJB之间也会相互调用,那我们如何在一个EJB内部调用其他的EJB呢??

 

在一个EJB的项目中,创建另一个接口:

  

public interface Other {

  public String sayMe();

}

 

然后创建该接口的实现类:

@Stateless

public class OtherBean implements Other{

 

    public String sayMe() {

       return "other";

    }

 

}

我们要在HelloWordBean.java中调用OtherBeansayMe()方法。那么如何在HelloWordBean中获得OtherBean??

如果直接在helloWordBean中直接new OtherBean()的话,是错误的。因为它不是EJB对象额。但我们可以通过另外另外两种方式获得。

1.    JNDI

HelloWordBeansayHello(String name)方法中加入如下代码:

try{

    InitialContext ctx = new InitialCOntext();

    Other other = (Other) ctx.lookup(“OtherBean/local”);

 return   other.sayMe();

}catch(NamingException e){

}

然后部署EJB,运行客户端,可以看到其运行结果正常。

2.    依赖注入(ejb注解)

HelloWorldBean中加入如下代码:

   @EJB(beanName=”OtherBean”) Other other;

注意该注解只能注解EJB。如果要注入其他的资源可采用

 @Resource TimeService timeService;

@Resource(mappedName=”java:xxx”)DataSource dataSource;(mappedName:用来指定datasource的名称)

 

0
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics