您的位置:首页 > 其它

2.一个EJB的小Demo

2016-07-09 12:55 363 查看
新建一个java普通项目即可



这里用到了Jboss,需要安装Jboss,然后进入jboss-4.2.3.GA\client目录,拷贝所有的jar包到本项目的lib下。

3个接口分别如下所示:

public interface Calculate {
//计算器接口,有个加法
public String add(Double a,Double b);

}


public interface CalculateLocal extends Calculate {
//此接口用于实现本地化,继承父类
}


public interface Other {
//另一个接口
public String hello();

}


下面是两个实现类:

//此类为无状态的本地和远程的bean

@Stateless
@Remote(Calculate.class)
@Local(CalculateLocal.class)
public class CalculateImpl implements Calculate,CalculateLocal{

/*使用其他的EJB
* 方式一,通过注解注入
* beanName指明要注入的是哪个ejb
* 如果有两个类都实现了这个接口,必须要指明注入的是哪个类
* 只有一个的话,可以不指明
* */
@EJB(beanName="OtherImpl")
Other other;
/**
* @Resource
* 注入资源
* */
//@Resource TimeService t;
//@Resource(mappedName="java:jndi的名字") DataSource da;

@Override
public String add(Double a, Double b) {
/*
* 方式二,通过jndi查找
*
Properties props = new Properties();
//设置jndi连接属性(jboss)
props.setProperty("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory");
//服务器的url(jboss)
props.setProperty("java.naming.provider.url", "127.0.0.1:1099");
try{
InitialContext ctx = new InitialContext(props);
Other other = (Other)ctx.lookup("OtherImpl/remote");//本地调用:CalculateImpl/local
other.hello();
}catch(Exception e){

}
*/

return "结果:"+a+b+other.hello();
}

}


@Stateless
@Remote(Other.class)
public class OtherImpl implements Other{

@Override
public String hello() {
System.out.println("hello...");
return "hello";
}

}


以上,服务端bean就开发好了,现在进行打包发布

右键项目-->Export-->java JAR file-->next




我们就看到了导出的jar包

任何将这个jar包放到jboss-4.2.3.GA\server\default\deploy目录下,启动jboss就可以了

下面是客户端开发



那3个接口还是要的,实现类就可以不要了,因为我们是通过远程访问服务器端的bean

public class Main {
public static void main(String[] args) {
Properties props = new Properties();
//设置jndi连接属性(jboss)
props.setProperty("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory");
//服务器的url(jboss)
props.setProperty("java.naming.provider.url", "127.0.0.1:1099");//本地IP
try{
InitialContext ctx = new InitialContext(props);
//jndi查找 远程
Calculate calculate = (Calculate)ctx.lookup("CalculateImpl/remote");//本地调用是:CalculateImpl/local
System.out.println(calculate.add(12D, 45D));//调用
}catch(Exception e){
System.out.println(e.getMessage());
}
}
}




这样,一个简单的分布式应用就部署执行成功了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: