很久没有看EJB3了,今天有空弄了个HelloWorld来耍耍,熟悉熟悉,加深些印象。
首先弄好环境,Eclipse JBOSS配置好环境变量。
接着就是code啦:
接口:HelloWorld.java
package org.eimhe.ejb3; public interface HelloWorld { public String SayHello(String name); }
实现接口:HelloWorldBean.java
package org.eimhe.ejb3; import javax.ejb.Remote; import javax.ejb.Stateless; @Stateless @Remote({HelloWorld.class}) public class HelloWorldBean implements HelloWorld{ public String SayHello(String name) { return name +"说:你好!世界,这是我的第一个EJB"; } }
创建个build.xml,使用ant来打包发布
<?xml version="1.0"?> <project name="HelloWorld" default="ejbjar" basedir="."> <property environment="env"/> <property name="src.dir" value="${basedir}/src"/> <property name="jboss.home" value="${env.JBOSS_HOME}"/> <property name="build.dir" value="${basedir}/build"/> <property name="build.classes.dir" value="${build.dir}/classes"/> <!-- Build classpath --> <path id="build.classpath"> <fileset dir="${jboss.home}/client"> <include name="*.jar"/> </fileset> <pathelement location="${build.classes.dir}"/> </path> <target name="prepare" depends="clean"> <mkdir dir="${build.dir}"/> <mkdir dir="${build.classes.dir}"/> </target> <target name="compile" depends="prepare" description="编译"> <javac srcdir="${src.dir}" destdir="${build.classes.dir}" debug="on" deprecation="on" optimize="off" includes="**"> <classpath refid="build.classpath"/> </javac> </target> <target name="ejbjar" depends="compile" description="创建EJB发布包"> <jar jarfile="${basedir}/HelloWorld.jar"> <fileset dir="${build.classes.dir}"> <include name="org/**/*.class"/> </fileset> </jar> </target> <target name="deploy" depends="ejbjar" description="f发布EJB"> <copy file="${basedir}/HelloWorld.jar" todir="${jboss.home}\server\default\deploy\"/> </target> <target name="clean"> <delete dir="${jboss.home}\server\default\deploy\HelloWorld.jar"/> </target> </project>
部署成功:
23:32:16,542 INFO [JBossASKernel] Created KernelDeployment for: HelloWorld.jar
23:32:16,589 INFO [JBossASKernel] installing bean: jboss.j2ee:jar=HelloWorld.jar,name=HelloWorldBean,service=EJB3
哈哈,来个junit测试下:HelloWorldTest.java
package junit.test; import static org.junit.Assert.*; import java.util.Properties; import javax.naming.InitialContext; import org.eimhe.ejb3.HelloWorld; import org.junit.BeforeClass; import org.junit.Test; public class HelloWorldTest { protected static HelloWorld helloWorld; @BeforeClass public static void setUpBeforeClass() throws Exception { Properties props = new Properties(); props.setProperty("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory"); props.setProperty("java.naming.provider.url", "localhost:1099"); InitialContext ctx = new InitialContext(props); helloWorld = (HelloWorld) ctx.lookup("HelloWorldBean/remote"); } @Test public void testSayHello() { String result = helloWorld.SayHello("test"); System.out.println("result : "+result); assertEquals("test说:你好!世界,这是我的第一个EJB", result); } }
第一个程序完成。