得到一个ejb对象有两种方式:JNDI查找和依赖注入。
工程结构如下:
各类的代码:
1 package cn.jvpy.ejb3;
2
3 public interface Other {
4 public String sayMe();
5 }
OtherBean.java
1 package cn.jvpy.ejb3.impl;
2
3 import javax.ejb.Stateless;
4
5 import cn.jvpy.ejb3.Other;
6
7 //此处没有标注@Local或者@Remote,则默认为@Local
8 @Stateless
9 public class OtherBean implements Other {
10
11 public String sayMe() {
12 return "other";
13 }
14
15 }
JNDI查找: HelloWorldBean.java
1 package cn.jvpy.ejb3.impl;
2
3 import javax.ejb.EJB;
4 import javax.ejb.Remote;
5 import javax.ejb.Stateless;
6 import javax.naming.InitialContext;
7 import javax.naming.NamingException;
8
9 import cn.jvpy.ejb3.HelloWorld;
10 import cn.jvpy.ejb3.Other;
11
12 @Stateless
13 @Remote(HelloWorld.class)
14 public class HelloWorldBean implements HelloWorld {
15
16 public String sayHello(String name) {
17
18 try {
19 InitialContext ctx = new InitialContext();
20 Other other = (Other) ctx.lookup("OtherBean/local");
21 return name + " said: Hello " + other.sayMe();
22 } catch (NamingException e) {
23 e.printStackTrace();
24 }
25
26 return null;
27 }
28
29 } 依赖注入:HelloWorldBean.java
1 package cn.jvpy.ejb3.impl;
2
3 import javax.ejb.EJB;
4 import javax.ejb.Remote;
5 import javax.ejb.Stateless;
6
7 import cn.jvpy.ejb3.HelloWorld;
8 import cn.jvpy.ejb3.Other;
9
10 @Stateless
11 @Remote(HelloWorld.class)
12 public class HelloWorldBean implements HelloWorld {
13 @EJB
14 Other other;
15
16 public String sayHello(String name) {
17 return name + " said: Hello " + other.sayMe();
18 }
19
20 } EJBClient:
EJBClient.java
1 package cn.jvpy.test;
2
3 import java.util.Properties;
4
5 import javax.naming.InitialContext;
6 import javax.naming.NamingException;
7
8 import cn.jvpy.ejb3.HelloWorld;
9
10 public class EJBClient {
11
12 public static void main(String[] args) {
13 try {
14 InitialContext ctx = new InitialContext();
15 HelloWorld helloWorld = (HelloWorld) ctx.lookup("HelloWorldBean/remote");
16 System.out.println(helloWorld.sayHello("Injector"));
17 } catch (NamingException e) {
18 System.out.println(e.getMessage());
19 }
20 }
21 } Inspiration:可以通过以上方式进行只有Local接口的EJB的单元测试?
具体步骤:添加一个TestHelper类,在此类中注入要测试的各local session bean,然后将该TestHelper标记为@Remote类型,通过该类的方法获取各ejb的实例。