在Flex中使用RemoteObject可以很容易地对Java对象进行RPC调用,但是其配置较为复杂。使用AMFPHP对PHP进行RPC调用只需要指定RemoteObject的destination和endpoint属性即可,而在BlazeDS环境下,需要创建ChannelSet和Channel对象。
通常的做法是使用一个xml文件来配置一个Java destination,Flex在编译的时候会根据配置信息来创建一个完整的RemoteObject对象。但是如果需要更改该RemoteObject对象的destination或者ChannelSet等属性,则需要重新编译,这样的话很是麻烦。
Spring的IOC容器可以很好解决这个问题,它把对象的创建方式声明在外部,然后由容器来动态生成。
使用我的Spring框架来实现这个想法。
1.创建远程的Java对象,编译成class文件放在文件夹WEB-INF\classes\demo下面。
package demo;
public class HelloBlazeDS{
public HelloBlazeDS(){
}
public String sayHello(String info){
return "[BlazeDS return] : "+info;
}
}
2.配置BalzeDS。
打开文件WEB-INF\flex\remoting-config.xml,向其中添加一个destination定义。
<destination id="HelloBlazeDS">
<properties>
<source>demo.HelloBlazeDS</source>
</properties>
</destination>
3.创建Spring的配置文件spring_config.xml。
<?xml version="1.0" encoding="utf-8"?>
<spring-config>
<beans>
<bean id="remoteBean" class="mx.rpc.remoting.mxml.RemoteObject">
<property name="destination" value="HelloBlazeDS"/>
<property name="channelSet" ref="channelSet"/>
</bean>
<bean id="channelSet" class="mx.messaging.ChannelSet">
<method name="addChannel">
<method-arg ref="channel"/>
</method>
</bean>
<bean id="channel" class="mx.messaging.channels.AMFChannel">
<property name="id" value="my-amf"/>
<property name="uri" value="http://localhost:8080/blazeds/messagebroker/amf"/>
</bean>
</beans>
</spring-config>
该配置文件声明了一个Bean名字叫remoteBean,它是一个RemoteObject对象,这个Bean还引用了channelSet和channel这两个Bean。
4.在Flex中使用Spring,下面是代码片段。
//导入加载配置文件的类ContextLoader
import com.colorhook.spring.context.ContextLoader;
private var contextLoader:ContextLoader;
private var remoteService:RemoteObject;
//初始化时加载配置文件
private function init():void{
contextLoader=new ContextLoader();
contextLoader.addEventListener("complete",onContextLoaderComplete);
}
//加载完成之后创建RemoteObject,并调用远程方法sayHello
private function onContextLoaderComplete(event:Event):void{
contextLoader.removeEventListener("complete",onContextLoaderComplete);
remoteService=contextLoader.contextInfo.getBean("remoteBean");
remoteService.sayHello.addEventListener(ResultEvent.RESULT,onSayHelloResult);
remoteService.sayHello("Spring and BlazeDS");
}
//输出返回结果
private function onSayHelloResult(event:ResultEvent):void{
Alert.show(String(event.result));
}