代码结构图如下:
客户端通过Spring的HttpInvoker,完成对远程函数的调用。涉及的类有:
客户端调用User类的服务UserService,完成对实现类UserServiceImpl的addUser(User u)方法调用。其中User类为普通Pojo对象,UserService为接口,UserServiceImpl为UserService的具体实现。代码如下: public interface UserService { void addUser(User u); }public class UserServiceImpl implements UserService {
public void addUser(User u) { System.out.println("add user ["+u.getUsername()+ "] ok !!!"); } }客户端调用时,主方法代码为:
public static void main(String[] args) throws Exception { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext( new String[] {"ApplicationContext.xml" }); UserService us = (UserService)ctx.getBean("ServletProxy"); us.addUser(new User("Hook1")); UserService us2 = (UserService)ctx.getBean("UrlPathProxy"); us2.addUser(new User("Hook2")); }其调用流程用时序图可表示为:
图中粉红色表示基于Url映射方式的配置时程序的处理流程,红色表示基于Servlet配置时的处理流程。 当以示基于Url映射方式的配置时,远程系统处理请求的方式同SpringMVC的controller类似,所有的请求通过在web.xml中的org.springframework.web.servlet.DispatcherServlet统一处理,根据url映射,去对应的【servlet名称-servlet.xml】文件中,查询跟请求的url匹配的bean配置;而基于Servlet配置时,由org.springframework.web.context.support.HttpRequestHandlerServlet去拦截url-pattern匹配的请求,如果匹配成功,去ApplicationContext中查找name与servlet-name一致的bean,完成远程方法调用。当使用URL映射配置时,实力配置如下(application-servlet.xml):
<bean name="/userHttpInvokerService" class="org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter"> <property name="service" ref="userService"/> <property name="serviceInterface" value="com.handou.httpinvoker.service.UserService"/> </bean>web.xml文件配置:
<servlet> <servlet-name>application</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>application</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping>如果使用基于Servlet的配置,web.xml文件配置如下:
<!-- 基于servlet配置时使用 ,根据请求的url匹配url-pattern,如果匹配成功,去ApplicationContext 中查找name与servlet-name一致的bean--> <servlet> <servlet-name>userHttpInvokerService</servlet-name> <servlet-class>org.springframework.web.context.support.HttpRequestHandlerServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>userHttpInvokerService</servlet-name> <url-pattern>/UserHttpInvokerService</url-pattern> </servlet-mapping>applicationContext.xml文件中配置如下:
<bean id="userService" class="com.handou.httpinvoker.service.UserServiceImpl" /> <!--第二种配置方式 --> <bean name="userHttpInvokerService" class="org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter"> <property name="service" ref="userService"/> <property name="serviceInterface" value="com.handou.httpinvoker.service.UserService"/> </bean>
两种方式,客户端配置均相同:
<bean id="ServletProxy" class="org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean"> <property name="serviceUrl"> <value>http://localhost:8080/HttpInvoke/UserHttpInvokerService</value> </property> <property name="serviceInterface"> <value>com.handou.httpinvoker.service.UserService</value> </property> </bean>具体可参考源码 :