服务器端:
1.创建一个javabean对象,需要实现Serializable接口。(如果只是传输字符串可以不用创建javabean对象)
1 | import java.io.Serializable; |
2 | public class User implements Serializable { |
3 | private static final long serialVersionUID = 1L; |
2.创建一个接口
01 | import com.my.po.User; |
02 | public interface IBaseService { |
08 | public String getHelloWord(String name); |
14 | public String getUser(User user); |
3.实现类
01 | import com.my.po.User; |
02 | import com.my.service.IBaseService; |
03 | public class BaseServiceImpl implements IBaseService { |
04 | public String getHelloWord(String name) { |
05 | return "欢迎" +name+ "的到来!!!" ; |
07 | public String getUser(User user) { |
08 | return "名字:" +user.getName()+ "--->" + "年龄:" +user.getAge(); |
4.创建一个spring配置文件 applicationContext.xml
01 | <? xml version = "1.0" encoding = "UTF-8" ?> |
02 | <? xml version = "1.0" encoding = "UTF-8" ?> |
08 | < bean id = "baseRmiService" class = "com.my.service.impl.BaseServiceImpl" /> |
09 | < bean id = "baseServiceExporter" class = "org.springframework.remoting.rmi.RmiServiceExporter" > |
11 | < property name = "service" ref = "baseRmiService" /> |
13 | < property name = "serviceName" value = "baseService" /> |
15 | < property name = "serviceInterface" value = "com.my.service.IBaseService" /> |
17 | < property name = "registryPort" value = "1200" /> |
5.main方法
1 | import org.springframework.context.support.ClassPathXmlApplicationContext; |
2 | import com.my.service.IBaseService; |
3 | public class BaseServiceTest { |
4 | public static void main(String[] args) { |
5 | ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( "applicationContext.xml" ); |
6 | IBaseService ibs = (IBaseService) context.getBean( "baseRmiService" ); |
7 | System.out.println( "baseRmiService启动..." ); |
将User.java和IBaseService.java打成jar包,放到客户端里面。
客户端:
1.创建一个spring配置文件 applicationContext.xml
01 | <? xml version = "1.0" encoding = "UTF-8" ?> |
07 | < bean id = "baseService" class = "org.springframework.remoting.rmi.RmiProxyFactoryBean" > |
11 | < property name = "serviceInterface" value = "com.my.service.IBaseService" /> |
2.main方法
01 | import org.springframework.context.support.ClassPathXmlApplicationContext; |
02 | import com.my.po.User; |
03 | public class ClientTest { |
04 | public static void main(String[] args) { |
05 | ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( "applicationContext.xml" ); |
06 | IBaseService ibs = (IBaseService) context.getBean( "baseService" ); |
07 | System.out.println(ibs.getHelloWord( "hao" )); |
08 | User user = new User(); |
09 | user.setName( "chenghao" ); |
11 | System.out.println(ibs.getUser(user)); |
现在运行ClientTest类就会在控制台打印出:
欢迎hao的到来!!! 名字:chenghao--->年龄:24