EJB Remote/Local 绑定和JNDI Lookup

来源:互联网 发布:linux vi退出保存 编辑:程序博客网 时间:2024/05/17 18:16
从同事那里学到一种方便的注解SessionBean的方式。
代码我放到github去了 
https://github.com/EdisonXu/Test/commit/703d49123dca9e666269771b08cc45dea6bff616
或者直接看路径 https://github.com/EdisonXu/Test/tree/master/remote-bean-test
其中test-local虽然打成了可执行jar包,但是依然无法直接通过Java -jar去执行。因为缺乏jboss相关依赖的包。我在网上没找到dependency,所以懒得搞了。直接把本地JBoss的包配到buildPath了,直接在eclipse中运行。

关键有两点:
1. 定义一个interface文件:

public interface RemoteTest {

public static final String NAME = "Test/RemoteTest";

public static final String JNDI_NAME = "Test/RemoteTest/remote";

public String getTest();

/**
* Local interface for session bean
*/
public static interface Local extends RemoteTest{}

/**
* Remote interface for session bean
*/
public static interface Remote extends RemoteTest{}

}

这样在注入的时候直接
@EJB
RemoteTest.Local localRemoteTest;
或者
@EJB
RemoteTest.Remote RemoteTest;

值得注意的是,如果这里直接用 RemoteTest 去作为类型,在加载这个包时会报错,会提示定义的RemoteTest.NAME的值,即Test/RemoteTest不唯一。导致部署失败。

2. 方便的JNDI Lookup
ejb3.1支持的几种JNDI LOOKUP:

java:global/

Get EJB instance by lookup global in java: Namespace.
Syntax: java:global/<ear-name>/<jar-name>/<bean-name>[!<fully-qualified-interface-name>]
Sample:
SampleBean implements SampleBeanRemote
interface SampleBeanRemote
{
JNDI_NAME="SampleBean";
}

sampleBeanInstance = (SampleBeanRemote)lookupByGlobal(SampleBeanLocal.JNDI_NAME);

java:app/

Get EJB instance by lookup app in java: Namespace.
Note: Only effect when the expect bean is in the same ear file with the POJO calling this method.
Syntax: java:app/<jar-name>/<bean-name>[!<fully-qualified-interface-name>]
Sample:
SampleBean implements SampleBeanLocal
interface SampleBeanLocal
{
NAME="SampleBean";
}

sampleBeanInstance = (SampleBeanLocal)lookupByApp(SampleBeanLocal.NAME);

java:module/

Get EJB instance by lookup module in java: Namespace.
Note: Only effect when the expect bean is in the same jar file with the POJO calling this method.
Syntax: java:module/<bean-name>[!<fully-qualified-interface-name>]
Sample:
SampleBean implements SampleBeanLocal
SampleBeanLocal
{
NAME="SampleBean";
}

sampleBeanInstance = (SampleBeanLocal)lookupByModule(SampleBeanLocal.NAME);

其中global, app 需要提供包名,但有时候我们会在包名里面包含版本号,这样每次修改都要去改源代码,很不方便。
而用上面提供的REMOTE/LOCAL绑定方式,现在直接用

RemoteTest rt = (RemoteTest)ctx.lookup(RemoteTest.JNDI_NAME);

方便快捷。

另外,还有一种方式是在jar包里面添加ejb-jar.xml。
里面显示的把去掉版本后的包名或别名写到 <moduleName>中去。这样用包名或别名替换掉原来带版本号的包名就行了。

原创粉丝点击