最简单的EJB示例

做一个EJB应用;首先需要导入支持EJB的包,本人也没弄清需要哪些包,总之,JBoos和WebLogic是支持EJB应用的!开发时,导入所有JBoos服务器client下所有的包。

使用Eclipse创建一个Java应用服务!

 

 

package com.xiva.cms.bean;

public interface HelloWorld {
	public String say(String name);
}

 

 

 

package com.xiva.cms.bean;

import javax.ejb.Remote;
import javax.ejb.Stateless;


@Stateless
@Remote(HelloWorld.class)
public class HelloWorldBean implements HelloWorld {

	@Override
	public String say(String name) {
		return name + ":Hello world!";
	}

}

 

 @Stateless表示是无状态会话服务;@Remote(HelloWorld.class)从Remote意思可知,是可远程调用。


编写好上面代码后,导出工程为Jar文件。启动Jboos成功后,将其拷入下面目录

 

 

E:\J2EEServer\jboss-4.2.3.GA\server\default\deploy
   

 注意最好不要放入带空格和中文名的路径中,以免带来不必要的麻烦!

 

 

最后编写调用类!

 

 

package com.xiva.cms.web;

//import java.util.Properties;

import javax.naming.InitialContext;
import javax.naming.NamingException;

import com.xiva.cms.bean.HelloWorld;

public class Person {


	public static void main(String[] args) {
		// TODO Auto-generated method stub
//		Properties prop = new Properties();
//		prop.setProperty("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory");
//		prop.setProperty("java.naming.provider.url", "localhost:1099");
		
		try {
//			InitialContext initContext = new InitialContext(prop);
			InitialContext initContext = new InitialContext();
			HelloWorld hello = (HelloWorld) initContext.lookup("HelloWorldBean/remote");
			System.out.println(hello.say("xiva"));
		} catch (NamingException e) {
			e.printStackTrace();
		}
	}

}

 

下面的配置文件放在class目录下面,查看源码VersionHelper12类中的getJndiProperties方法可知是使用Class--getResourceAsStream方法来加载配置文件的!

 

 

java.naming.factory.initial = org.jnp.interfaces.NamingContextFactory
java.naming.provider.url = localhost:1099

 假如你不编写这个配置文件,也可以使用Properties 类自己编写配置信息!去掉代码注释即可!

你可能感兴趣的:(java,cms,bean,应用服务器,ejb)