BANGALORE, INDIA: Since its introduction with JDK 1.1, RMI has been a dominant protocol for connecting Java application on both ends of the wire. However, RMI involves a lot of boilerplate; for example, a remote interface must extend the java.rmi.Remote interface, generate stubs and skeletons, complicated lookup, handle RemoteException and MalformedUrlException, etc. So, you can well imagine the complexity involved in using RMI for this job! Spring simplified the RMI development experience by providing service exporters out of the box.
Furthermore, Spring provides a seamless integration with HTTP protocol for exposing POJO components as remote services, something that was not present earlier and one which has made developers' life easy. In a series of two articles, we'll explore these two popular techniques (RMI and HTTP), provided by the Spring framework and that help expose POJOs as remote services.
Transparent remoting using RMI
In order to transparently expose POJOs as remote services, Spring provides RmiServiceExporter to export Spring beans over the RMI protocol and RmiProxyFactoryBean to consume
remote services. In this article, we'll expose a simple service as an RMI service. To begin with, we'll write a service interface and an implementation class, as shown below:
package com.pcquest.remoting.service;
public interface rmservice
{
String getResult(String s);
}
As shown in the preceding code snippet, the service doesn't extend the java.rmi.Remote interface and none of its methods throw java.rmi.Remote Exception; this removes the boilerplate.
package com.pcquest.remoting.service;
public class rmserviceimpl implements rmservice
{
public rmserviceimpl(){
}
public String getResult(String a)
{
return "Hi "+a;
}
}
The service implementation class is simple. As opposed to traditional RMI service implementation class, the rmserviceimpl POJO doesn't extend the UnicastRemoteObject. However, you need to still wire the dependencies in the Spring configuration file, as shown here:
<bean class="org.springframework.remoting.rmi.RmiServiceExporter">
<property name="service" ref="rmservice"/>
<property name="serviceName">
<value>MyService</value>
</property>
<property name="serviceInterface">
value>com.pcquest.remoting.service.rmservice</value>
</property>
<property name="registryPort" value="1199"/>
</bean>
<bean id="rmservice" class="com.pcquest.remoting.service.rmserviceimpl">
</bean>
The plumbing code is simple; as discussed before, the RmiService Exporter is used to expose any Spring managed bean as an RMI service. The POJO bean is wrapped inside an adapter class which implements the remote interface as indicated by the 'service Interface.'
Furthermore, the RmiServiceExporter registers the same under the name 'MyService' and binds with port 1199. Notice that the remote service implementation is injected into the 'service' property through Dependency Injection (DI).