接着上一节Hessian学习(3)——客户端使用spring,发现正常使用的时候好像很少会直接getBean,而是将这个Bean注入到一些Util里面。
1.新建一个客户端项目,此处命名为Hessiaclient3;
2.导入必要的jar:
aopalliance-1.0.jar
commons-logging-1.1.1.jar
hessian-4.0.7.jar
junit-4.10.jar
spring-aop-3.1.1.RELEASE.jar
spring-asm-3.1.1.RELEASE.jar
spring-beans-3.1.1.RELEASE.jar
spring-context-3.1.1.RELEASE.jar
spring-context-support-3.1.1.RELEASE.jar
spring-core-3.1.1.RELEASE.jar
spring-expression-3.1.1.RELEASE.jar
spring-web-3.1.1.RELEASE.jar
3.将服务器的接口代码放到HessianClient3,实现代码不需要:
public interface HelloService {
public String helloWorld(String msg);
}
4.配置hessia-client.xml:
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config />
<context:component-scan base-package="com.cmsz.upay.hessian.*"></context:component-scan>
<!-- 客户端Hessian代理工厂Bean -->
<bean id="myClient" class="org.springframework.remoting.caucho.HessianProxyFactoryBean">
<!-- 地址 -->
<property name="serviceUrl">
<value>http://localhost:28080/HessianServer2/hessian/hello</value>
</property>
<!-- 接口定义 -->
<property name="serviceInterface">
<value>com.cmsz.upay.hessian.service.HelloService</value>
</property>
</bean>
</beans>
5.编写一个工具类,调用hessian的服务:
@Service
public class HessianUtil {
@Autowired
HelloService service ;
public void test() {
System.out.println(service.helloWorld("HessianUtil!"));
}
}
6.编写测试类:
public class Test {
@org.junit.Test
public void test() {
ApplicationContext context = new ClassPathXmlApplicationContext("hessian-client.xml");
System.out.println(context);
HessianUtil util = context.getBean(HessianUtil.class);
util.test();
}
}
7.运行结果如下:
总结:
1.在hessian-client.xml配置了服务的接口,在HessianUtil.java只要注入这个接口,在调用这个接口的方法时,客户端就知道将消息发送到:
<!-- 地址 -->
<property name="serviceUrl">
<value>http://localhost:28080/HessianServer2/hessian/hello</value>
</property>
代码地址:csdn code