现在大部分的应用都使用到了Spring框架,我们一般使用Spring容器来管理对象的创建。我们同样可以将Hessian与Spring整合,方便管理,简化代码的开发。
Spring默认支持Hessian,可以通过Spring的官方文档查询相关资料,这个文档就在下载的压缩包里。文档路径如下:
spring-framework-3.2.0.RELEASE-dist\spring-framework-3.2.0.RELEASE\docs\spring-framework-reference\pdf\spring-framework-reference.pdf
这是个pdf文档,打开文档,左边有文档结构,
框出来的就是关于远程方法调用的整合部分。
以之前入门案例为例进行整合。
确保导入了Spring的必须的包。
首先保证client中有需要的接口,如果有JavaBean,那么这个JavaBean必须实现Serilizable接口,否则报错。
然后在classpath创建applicationContext.xml的Spring核心配置文件。在这个配置文件中配置这个接口的信息,比如配置URL,配置接口等:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
">
<!-- Hessian -->
<bean id="helloService" class="org.springframework.remoting.caucho.HessianProxyFactoryBean">
<!-- 配置要访问的系统的URL路径 -->
<property name="serviceUrl" value="http://localhost:8080/server/hello"/>
<!-- 配置要使用哪个接口中的方法,将这个接口的全限定名称配置进来 -->
<property name="serviceInterface" value="service.HelloService"/>
</bean>
</beans>
最后编写测试用例,使用Spring提供的Junit测试:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext.xml")
public class SpringTest {
@Resource(name="helloService")
private HelloService helloService;
@Test
public void springDemo() {
System.out.println(helloService.sayHello());
}
}
整合完毕。