interface定义的时候就决定该接口是本地使用、还是远程使用。很多官方示例代码提供的都是在interface上加本地、还是远程
@Local
public interface Register
{
public void register();
public void invalid();
public String getVerify();
public void setVerify(String verify);
public boolean isRegistered();
public void destroy();
}
实现只管实现接口,不用管是本地使用还是远程使用
@Stateful
@Scope(EVENT)
public class RegisterAction implements Register
{
更好的实践是interface上不定义本地、远程,在实现类上定义本地、远程,这样interface也就可以被非ejb实现了。
public interface Register
{
public void register();
。。。
}
@Stateful
@Local
public class RegisterAction implements Register
{
当一个接口既可以远程调用也可以本地调用时,只需定义远程实现即可,ejb容器会对本地部署的bean自动进行本地调用。
在实际应用中,一个无状态Session Bean都应该实现Remote与Local接口。当会话Bean的某些方法只供EJB
容器内部调用而不对外暴露时,可以把他定义在Local接口。本节介绍如何开发一个具有Remote与Local 接口的
无状态Session Bean。开发前先介绍一下两个接口具有的方法,两者都含有方法Add(int a, int b),而Local接口含
有一个自己的方法:getResult()。下面是例子的源代码。
定义远程接口:Operation.java
//author:lihuoming
package com.foshanshop.ejb3;
public interface Operation {
public int Add(int a, int b);
}
定义本地接口:LocalOperation.java,本地接口具有远程接口的所有方法,另外有自己的方法getResult()
//author:lihuoming
package com.foshanshop.ejb3;
public interface LocalOperation extends Operation {
public int getResult();
}
实现本地接口与远程接口的会话Bean:OperationBean.java
//author:lihuoming
package com.foshanshop.ejb3.impl;
import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import com.foshanshop.ejb3.LocalOperation;
import com.foshanshop.ejb3.Operation;
@Stateless
@Remote ({Operation.class})
@Local ({LocalOperation.class})
public class OperationBean implements Operation, LocalOperation {
private int total = 0;
private int addresult = 0;
public int Add(int a, int b) {
addresult = a + b;
return addresult;
}
public int getResult() {
total += addresult;
return total;
}
}