服务器端和客户端需要在pom.xml(我使用了Maven构建项目,你也可以手动添加依赖)添加Spring的context依赖
org.springframework
spring-context
4.0.3.RELEASE
它会自动添加相关依赖如:spring-beans等,如下图
并引用远程接口项目进来,服务器端HelloImpl.java
package net.oseye.DemoSpringRMI.Server;
import net.oseye.DemoSpringRMI.RemotInterface.IHello;
public class HelloImpl implements IHello {
public String sayHello(String name) {
return "Hello,"+name;
}
}
可以看到也不用继承UnicastRemoteObject类了。看下spring的配置文件applicationcontext.xml吧
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
服务器端使用了org.springframework.remoting.rmi.RmiServiceExporter类,并注入相关属性:serviceName、service、serviceInterface、registryPort等,还有更多的属性可以查看spring类库如:
主程序App.java
package net.oseye.DemoSpringRMI.Server;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App
{
@SuppressWarnings("resource")
public static void main( String[] args )
{
new ClassPathXmlApplicationContext("applicationcontext.xml");
System.out.println("服务器启动成功");
}
}