1.业务接口类及其实现

/**
 * 定义一个远程接口
 */
public interface HelloService
{
    /**
     * 需要远程调用的方法
     * @param msg
     * @return
     */
    String sayHello(String msg);
}


public class HelloServiceImpl implements HelloService
{
    public String sayHello(String msg)
    {
        return "server received the msg : " + msg;
    }
}


2.RmiServiceExporter(服务端)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

    <!--RMI的服务实现类-->
    <bean id="helloService" class="com.rmi.spring.HelloServiceImpl" />

    <bean id="serviceExporter" class="org.springframework.remoting.rmi.RmiServiceExporter">
        <!--配置RMI的服务实现类-->
        <property name="service" ref="helloService" />
        <!--配置RMI的服务接口-->
        <property name="serviceInterface" value="com.rmi.spring.HelloService"/>
        <!--暴露的对外服务名-->
        <property name="serviceName" value="hello" />
        <!--服务本地注册端口-->
        <property name="registryPort" value="9123" />
        <!--服务对外暴露端口-->
        <property name="servicePort" value="9123" />
        <!--注册服务-->
        <property name="alwaysCreateRegistry" value="true" />
    </bean>

</beans>


3.RmiProxyFactoryBean(客户端)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

    <bean id="helloService" class="org.springframework.remoting.rmi.RmiProxyFactoryBean">
        <property name="serviceUrl" value="rmi://localhost:9123/hello" />
        <property name="serviceInterface" value="com.rmi.spring.HelloService"/>
    </bean>

</beans>


4.测试

public class HelloServer
{
    public static void main(String[] args)
    {
        new ClassPathXmlApplicationContext("spring-rmi-server.xml");
        System.err.println("rmi 服务启动!");
    }
}
public class HelloClient
{
    public static void main(String[] args)
    {
        ApplicationContext applicationContext 
        = new ClassPathXmlApplicationContext("spring-rmi-client.xml");

        HelloService helloService 
        = (HelloService)applicationContext.getBean("helloService");

        System.err.println(helloService.sayHello("测试测试!"));
    }
}


注:Registry服务的注册问题,有时会出现服务启动报错.