开发具有远程接口的无状态会话Bean
l 第一步:创建业务接口类和业务接口实现类HelloWorld.java
package com.hello.ejb3;
import javax.ejb.Remote;
@Remote
public interface HelloWorld {
public String hello(String name);
}
//@Remote:通过注解说明HelloWorld是一个远程接口
HelloWorldImpl.java
package com.hello.ejb3.impl;
import javax.ejb.Stateless;
import com.hello.ejb3.HelloWorld;
@Stateless
public class HelloWorldImpl implements HelloWorld {
@Override
public String hello(String name) {
return "hello," + name;
}
}
//@Stateless:表示HelloWorldImpl是无状态会话Bean
l 第二步:将完成的代码打成JAR包,并把JAR复制到jboss-5.0.1.GA 安装目录的“…\server\default\deploy”目录下。
l 第三步:启动JBOSS。
l 第四步:编写客户端程序访问EJB
package com.hello.test;
import java.util.Properties;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import com.hello.ejb3.HelloWorld;
public class EJBClient {
public static void main(String[] args) {
//设置EJB JNDI属性
Properties config = new Properties();
config.setProperty("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory");
config.setProperty("java.naming.provider.url", "localhost:1099");
try{
//初始化JNDI配置上下文
InitialContext ctx = new InitialContext(config);
//调用远程接口
HelloWorld helloworld = (HelloWorld)ctx.lookup("HelloWorldImpl/remote");
System.out.println(helloworld.hello("vince"));
}catch(NamingException ex){
ex.printStackTrace();
}
}
}
在第四步的代码中,我们通过硬编码的方式为EJB的JNDI属性设值,这样的编码方式大大降低了代码的灵活性,所以我们还可以通过一个属性文件的方式为JNDI属性设值:
java.naming.factory.initial= org.jnp.interfaces.NamingContextFactory
java.naming.provider.url= localhost:1099
EJB初始化JNDI配置上下文时,会自动的寻找根目录下的jndi.properties文件。
这样我们的客户端代码就可以简化为:
package com.hello.test;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import com.hello.ejb3.HelloWorld;
public class EJBClient {
public static void main(String[] args) {
try{
//初始化JNDI配置上下文
InitialContext ctx = new InitialContext();
//调用远程接口
HelloWorld helloworld = (HelloWorld)ctx.lookup("HelloWorldImpl/remote");
System.out.println(helloworld.hello("vince"));
}catch(NamingException ex){
ex.printStackTrace();
}
}
}
OK!恭喜你!现在我们可以测试一下!