若要使用ejb,必须要有ejb的容器,现在的容器有jboss,weblogic等,现使用jboss编写第一个ejb程序。
到http://downloads.sourceforge.net/sourceforge/jboss/地址去下载jboss,ejb3必须下jboss4以上的版本,ejb2下载jboss3就可以了。需在工程中引入jbossall-client.jar。
首先创建一个ejb项目,注意需选择ejb3.
创建一个接口
public interface HelloWorld { public String SayHello(String name); }
然后新建一个无关态会话Bean,一般的命名规则是:接口名+Bean。实现上面的接口要加入两个注释@Remote和@Stateless。
@Stateless表示无状态会话Bean,@Remote表示这个无状态会话Bean的remote接口。。无状态会话Bean 是一个简单的POJO(纯粹的面向对象思想的java 对象),EJB3.0 容器自动地实例化及管理这个Bean。HelloWorldBean.java代码如下:
import javax.ejb.Remote; import javax.ejb.Stateless; @Stateless @Remote ({HelloWorld.class}) public class HelloWorldBean implements HelloWorld { public String SayHello(String name) { return name +"说:Hello World."; } }
17:33:58,062 INFO [DLQ] Bound to JNDI name: queue/DLQ 17:33:58,203 INFO [ConnectionFactoryBindingService] Bound ConnectionManager 'jboss.jca:service=ConnectionFactoryBinding,name=JmsXA' to JNDI name 'java:JmsXA' 17:33:58,609 INFO [JmxKernelAbstraction] creating wrapper delegate for: org.jboss.ejb3.stateless.StatelessContainer 17:33:58,625 INFO [JmxKernelAbstraction] installing MBean: jboss.j2ee:jar=TestEJB3.jar,name=HelloWorldBean,service=EJB3 with dependencies: 17:33:58,906 INFO [EJBContainer] STARTED EJB: com.sample.HelloWorldBean ejbName: HelloWorldBean 17:33:58,968 INFO [EJB3Deployer] Deployed: file:/E:/developTools/jboss-4.2.0.GA/server/default/deploy/TestEJB3.jar/ 17:33:59,015 INFO [TomcatDeployer] deploy, ctxPath=/jmx-console, warUrl=.../deploy/jmx-console.war/ 17:33:59,281 INFO [Http11Protocol] Starting Coyote HTTP/1.1 on http-127.0.0.1-8080 17:33:59,312 INFO [AjpProtocol] Starting Coyote AJP/1.3 on ajp-127.0.0.1-8009 17:33:59,343 INFO [Server] JBoss (MX MicroKernel) [4.2.0.GA (build: SVNTag=JBoss_4_2_0_GA date=200705111440)] Started in 17s:15ms说明发布成功,然后可以到http://localhost:8080>> JMX Console >> service=JNDIView >>invoke>>Global JNDI Namespace找到发布的响应服务,若没有找到jndi,则发布服务失败。成功后即可以打开客户端去访问。
import java.util.Properties; import javax.naming.InitialContext; public class HelloWorleClient { public static void main(String[] args) { Properties props = new Properties(); props.setProperty("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory"); props.setProperty("java.naming.provider.url", "localhost:1099"); props.setProperty("java.naming.factory.url.pkgs", "org.jboss.naming"); //props.setProperty("", ""); System.getProperties(); try { InitialContext ctx = new InitialContext(props); HelloWorld helloworld = (HelloWorld) ctx.lookup("HelloWorldBean/remote"); System.out.println(helloworld.SayHello("大家")); } catch (Exception ex) { System.out.println(ex.getMessage()); } } }在JBoss容器中发布TestEJB3,然后执行HelloWorldClient.java将得到“大家说:Hello World.”结果。