Hello EJB3

开发具有远程接口的无状态会话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();
		}
	}
}

 

在第四步的代码中,我们通过硬编码的方式为EJBJNDI属性设值,这样的编码方式大大降低了代码的灵活性,所以我们还可以通过一个属性文件的方式为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!恭喜你!现在我们可以测试一下!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值