# Spring Remote Method Invocation (RMI) Client example

In 
Published 2022-12-03

This tutorial explains to you how to create a Spring Remote Method Invocation (RMI) Client and also provides you with an example.

RMI stands for Remote Method Invocation. It is a mechanism that allows an object residing in one Java container to access/invoke an object running on another Java container (generally on another host, but not necessarily). The Object instances are serialized and send over the network.

In order to access the remote object, the RMI server must declare an exporter and the client a proxy.

In this tutorial you will have an example of using Remote Method Invocation (RMI) in Spring from a client.

For creating the example, you have to create a simple Maven & Spring project.

Here you have the dependencies you need in the pom.xml file:

Now you have to add the following classes to your projects:

package com.example.interfaces;
 
public interface IMyServiceA {
    public String addNumbers(int val1, int val2);
}
package com.example.config;
 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.remoting.rmi.RmiProxyFactoryBean;
 
import com.example.interfaces.IMyServiceA;
 
@Configuration
@ComponentScan("com.example.*")
public class SpringContextConfig {
 
    @Bean
    public RmiProxyFactoryBean rmiProxy() {
        RmiProxyFactoryBean proxy = new RmiProxyFactoryBean();
         
        proxy.setServiceUrl("rmi://localhost:4400/ServiceA");
        proxy.setServiceInterface(IMyServiceA.class);
        return proxy;
    }
}
package com.example.main;
 
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
 
import com.example.config.SpringContextConfig;
import com.example.interfaces.IMyServiceA;
 
public class Main {
    public static void main(String [] arg) {
         AnnotationConfigApplicationContext context =               
                 new AnnotationConfigApplicationContext(SpringContextConfig.class);
          
         IMyServiceA service = context.getBean(IMyServiceA.class);
          
         System.out.println(service.addNumbers(10, 20));
    }
}

When you run the project you will see the following log: