Spring rmi的简单demo

来源:互联网 发布:电子书在线制作软件 编辑:程序博客网 时间:2024/05/20 18:42
(1)定义接口:
Java代码 复制代码 收藏代码
  1. package com.logcd.spring.rmi;   
  2.   
  3. public interface HelloService {   
  4.     public String doHello(String name);   
  5. }  

(2)接口实现:
Java代码 复制代码 收藏代码
  1. package com.logcd.spring.rmi;   
  2.   
  3. public  class HelloServiceImpl implements HelloService{   
  4.   
  5.     public String doHello(String name) {   
  6.         return "Hello , " + name;   
  7.     }   
  8.   
  9. }  

(3)rmi-server.xml
Java代码 复制代码 收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>    
  2. <!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN"    
  3.   "http://www.springframework.org/dtd/spring-beans.dtd">    
  4.   
  5. <beans>    
  6.     <bean id="helloService" class="com.logcd.spring.rmi.HelloServiceImpl"/>   
  7.   
  8.     <!--RmiServiceExporter显示地支持使用RMI调用器暴露任何非RMI服务-->   
  9.     <bean id="serviceExporter"    
  10. class="org.springframework.remoting.rmi.RmiServiceExporter">   
  11.   
  12.         <property name="service" ref="helloService"/>   
  13.         <property name="serviceInterface"  
  14.            value="com.logcd.spring.rmi.HelloService"/>   
  15.         <!--定义要暴露的服务名可以与输出的bean不同名,客户端通过这个名字来调用服务-->   
  16.         <property name="serviceName" value ="HelloService"/>   
  17.         <!--覆盖RMI注册端口号(1099),通常应用服务器也会维护RMI注册,最好不要冲突-->   
  18.         <property name="registryPort" value="1199"/>   
  19.     </bean>   
  20.        
  21. </beans>  

(4)rmi-client.xml
Java代码 复制代码 收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>    
  2. <!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN"  
  3.    "http://www.springframework.org/dtd/spring-beans.dtd">   
  4. <beans>   
  5.     <!--使用RmiProxyFactoryBean连接服务端-->   
  6.      <bean id="serviceProxy"    
  7.                class="org.springframework.remoting.rmi.RmiProxyFactoryBean">   
  8.   
  9.         <property name="serviceUrl"  
  10.                     value="rmi://localhost:1199/HelloService"/>    
  11.         <property name="serviceInterface"  
  12.                   value="com.logcd.spring.rmi.HelloService"/>   
  13.      </bean>   
  14. </beans>  

(5)测试
Java代码 复制代码 收藏代码
  1. package com.logcd.spring.rmi;   
  2.   
  3. import org.springframework.context.ApplicationContext;   
  4. import org.springframework.context.support.ClassPathXmlApplicationContext;   
  5.   
  6. public class TestSpringRMI {   
  7.        
  8.     public static void main(String args[]){   
  9.        ApplicationContext context= new ClassPathXmlApplicationContext(   
  10.                 new String[]{"rmi-server.xml","rmi-client.xml"});    
  11.           
  12.        HelloService service = (HelloService)context.getBean("serviceProxy");   
  13.           
  14.        System.out.println(service.doHello("logcd"));   
  15.     }   
  16.        
  17. }  
原创粉丝点击