Spring HttpInvoker(一)

一: 暴露服务(Spring mvc暴露服务)

package com.xx.service;

public interface ISayHelloService {

	/**
	 * @param name
	 * @return
	 */
	 String doSayHello(String name);
} 
package com.xx.service.impl;

import com.xx.service.ISayHelloService;
public class DefaultSayHelloServiceImpl implements ISayHelloService {

	public String doSayHello(String name) {
		return "hello, " + name;
	}
}
通过Spring mvc暴露服务
web.xml
<!-- DispatcherServlet -->
	<servlet>
		<servlet-name>Spring-DispatcherServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/config/applicationContext-server.xml</param-value>
		</init-param>
	</servlet>
	
	<servlet-mapping>
		<servlet-name>Spring-DispatcherServlet</servlet-name>
		<url-pattern>*.service</url-pattern>
	</servlet-mapping>
applicationContext-server.xml
	<bean id="defaultSayHelloService" class="com.xx.service.impl.DefaultSayHelloServiceImpl" />
	
	<bean id="sayHelloServiceExporter" class="org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter" >
		<property name="service" 			ref="defaultSayHelloService" />
		<property name="serviceInterface" 	value="com.xx.service.ISayHelloService" />
	</bean>
		
	<bean id="simpleUrlHandlerMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
	   	<property name="urlMap">
			<map>
			  <entry key="/defaultSayHelloService.service" value-ref="sayHelloServiceExporter" />
			</map>
		</property>
	</bean>	

二:引用服务

package com.xx.service;

public interface ISayHelloService {

	/**
	 * @param name
	 * @return
	 */
	 String doSayHello(String name);
}
applicationContext-client.xml
	<bean id="sayHelloService"  class="org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean">
		<property name="serviceUrl" 		value="http://localhost:8080/httpInvoker/defaultSayHelloService.service" />
		<property name="serviceInterface" 	value="com.xx.service.ISayHelloService"/>
	</bean>
public class ClientMain {
	
	private static final DefaultListableBeanFactory beanFactory;
	
	static {
		beanFactory = new DefaultListableBeanFactory();
		BeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
		Resource resource = new ClassPathResource("applicationContext-client.xml");
		beanDefinitionReader.loadBeanDefinitions(resource);
	}
	
	public static void main(String[] args) {
		ISayHelloService sayHelloService = beanFactory.getBean("sayHelloService", ISayHelloService.class);
		System.out.println(sayHelloService.doSayHello("王五"));
	}
}
posted on 2012-04-09 15:31  YangJin  阅读(155)  评论(0编辑  收藏  举报