EJB Remote/Local 绑定和JNDI Lookup

从同事那里学到一种方便的注解SessionBean的方式。
代码我放到github去了 
其中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>中去。这样用包名或别名替换掉原来带版本号的包名就行了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值