Spring remoting, client side
 
I had recently implemented an RMI based comunication between two applications. The server is a Spring based application. A very good and quick solution in this scenario is to expose the RMI services with Spring-Remoting. Spring will wrap your service with an RMI-aware stub on the fly, so you don’t even need to generate stubs and skeletons with rmic. What is not clear in the documentation is that the RMI client willing to use the Spring-Remote RMI service must be also a Spring application. The reason is that what is registered in the RMI registry is not a classic RemoteObject.
 
But it’s easy to hack a solution on the client having just spring-remote-2.0.5.jar in the classpath. You’re not really using dependency injection, the main goal of Spring, but just the RMI library to unwrap what Spring has wrapped on the server side.
 
import org.springframework.remoting.rmi.RmiInvocationWrapper_Stub;
import org.springframework.remoting.support.RemoteInvocation;


Registry registry = 
    LocateRegistry.getRegistry("host""1099");

RmiInvocationWrapper_Stub rmStub = 
    (RmiInvocationWrapper_Stubregistry.lookup("ServiceName");

RemoteInvocation remoteInvocation = 
    new RemoteInvocation(
        "MethodName"
        new Class[]{}
        new Object[]{});

Object result = rmStub.invoke(remoteInvocation);

free hit counter

 
As you can see from the snippet above, you need two Spring-Remote classes. The way you call the remote method is reflective. In other words, Spring-Remote exports as the RMI object something similar to the java.lang.reflect.Method class. Exactly as reflection, you lose the static type checking and you have to cast the resulting Object to something you can use. Anyway, I don’t think it’s a big problem to use the reflective invocation if you can’t spring-ify the client application for some reasons. Happy coding.
 
Reblog Details
Thursday, June 7, 2007