这里我根据网上找到的一个例子来分析spring的invoke用法
(例子链接:http://blog.csdn.net/up2pu/article/details/5415647)
对于初学者而言,在ssh中一般都是将dao,service,action全都塞到application-Context.xml中管理,但是当项目做大后就会发现application-Context.xml显得很拥挤,所以当然需要分解,但是初学者就会问,这样的话action如何得到service的接口呢?这里就用到了远程的调用。
我测试的时候需要的包是commons-logging.jar,spring.jar,spring-webmvc.jar
该链接的地址的内容是首先创建一个接口和一个实现类,功能很简单,就是返回一个“test”的字符串,
首先创建一个web项目,我命名为httpInvokeExampleServer
接下来就是将该service注册到applicationContext.xml或者也可以自定一个xml,只要待会儿在web.xml中注册时指定就行了。
<bean id="personService" class="service.impl.PersonServiceImpl" />
当然这并不是给外界的接口,这只是一个内部的注册,接下来就创建一个接口给外部调用。
<bean id="serviceExporter" class="org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter">
<property name="service" ref="personService" />
<property name="serviceInterface" value="service.IPersonService" />
</bean>
按照例子的理解,就是注册一个bean,它的类时库包中的,有两属性,service和serviceInterface,前者就是使用注册在spring中的personService,后者就是包中的接口。忘了说,我创了一个service包用于存放接口,一个service.impl存放实现类
但是我们呢最后是要根据网络地址去找到相应的service,所以接下来就是干这事的
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/person.service">serviceExporter</prop>
</props>
</property>
</bean>
也是先注册一个库包中的bean,属性就是一个映射。什么映射呢,就是若网络地址的为person.service时就会去调用serviceExporter这个bean。
由于我们最后是要根据网址寻找的,这样就少不了web.xml中的注册了
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>*.service</url-pattern>
</servlet-mapping>
这一段的意思就是当有一个是以.service结尾的请求的话,就会去调用dispatcherServlet,同时在里面初始化了contextConfigLocation。
这样我们就将service的服务创建了,接下来我们看如何调用。
再创建一个项目httInvokeExampleClient
将service包从上面的项目中copy过来
创建一个xml
<beans>
<bean id="personServiceProxy" class="org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean">
<property name="serviceUrl" value="http://localhost:8080/httpInvokeExampleServer/person.service"></property>
<property name="serviceInterface" value="service.IPersonService"></property>
</bean>
</beans>
这句话的意思就是去寻找http://localhost:8080/httpInvokeExampleServer/person.service这个服务,看到没?这就是根据网址来寻找的。
最后来测试一下
ApplicationContext context = new ClassPathXmlApplicationContext("httpinvoker-client.xml");
IPersonService service = (IPersonService) context.getBean("personServiceProxy");
String result = service.queryPersonName();
System.out.println(result);
测试是首先开启前一个项目,然后再运行这个项目中的test。