---
title: "通过注解方式注入并使用其他EJB或者服务(八).doc"
author: "tigers20010"
date: "2010-04-11T01:38:52Z"
tags: []
categories: ["企业架构"]
slug: "ejb-doc"
draft: false
lastmod: "2010-04-11T01:38:52Z"
id: 641019
url: "https://itjava2000.iteye.com/blog/641019"
---

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

 

在一个EJB的项目中，创建另一个接口：

  

**public** **interface** Other {

  **public** String sayMe();

}

 

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

@Stateless

**public** **class** OtherBean **implements** Other{

 

    **public** String sayMe() {

       **return** "other";

    }

 

}

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

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

1.    JNDI

在HelloWordBean的sayHello(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的名称)