AS3 IOC框架Spring Actionscript 的使用总结
Spring Actionscript 是众多围绕依赖注入提供解决方案的Flex控制反转框架之一
AS3 下经典的IOC框架有Spring ActionScript、Parsley、Flicc和Swiz,由于我对JAVA spring IOC机制较为熟悉,所以选择了 Spring ActionScript。
主要有XML配置(XML)和注释元数据(Metadata)配置两种方式,下面一一介绍,例子是基于spring AS 2.0.1版本展开的。--流子
1.从Spring Actionscript 主页下载依赖包
spring-actionscript-core-X.X.X.swc
spring-actionscript-flex-X.X.X.swc
另有as3commons依赖包需要下载。建议下载这个
Spring Actionscript X.X.X Full (with dependencies and Flex extensions)
2.1 XML配置方式
配置文件application-context.xml
<?xml version="1.0" encoding="UTF-8"?> <objects xmlns="http://www.springactionscript.org/schema/objects" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springactionscript.org/schema/objects http://www.springactionscript.org/schema/objects/spring-actionscript-objects-2.0.xsd"> <object id="ConfigManager" class="com.yimi.fairy.client.ConfigManager" init-method="initialize"> <!--<constructor-arg ref="authenticationService"/> 构造函数时引入 --> </object> <object id="RoleManager" class="com.yimi.fairy.client.service.role.RoleManager" init-method="initialize"> <property name="configManager" ref="ConfigManager" /> </object> <object id="ResourceManager" class="com.yimi.fairy.client.res.ResourceManager"></object> <object id="JobManager" class="com.yimi.fairy.client.job.JobManager"></object> <object id="RoleDataTemplateManager" class="com.service.role.RoleDataTemplateManager"> <constructor-arg ref="ResourceManager"/> </object> </objects>
程序载入:
var context:XMLApplicationContext=new XMLApplicationContext("application-context.xml"); context.addEventListener(Event.COMPLETE, this.handleComplete); context.load();
对容器中对象读取:
var configManager:ConfigManager=context.getObject("ConfigManager");
2.2 注释元数据(Metadata)配置方式
优点:把application-context.xml 完全干掉,完全通过注释方式实现。它是对加载进来的SWF文件进行类扫描把[Component] 或者[Configuration] 读取并解析进IOC容器。
首先,要添加编译参数 -keep-as3-metadata+=Component,Invoke,Inject,Autowired
程序载入:
var rootViews:Vector.<DisplayObject> = new <DisplayObject>[display]; var context:MetadataApplicationContext= new MetadataApplicationContext(rootViews); context.addEventListener(Event.COMPLETE, this.handleComplete); context.load();对象配置:
[Component(id="roleDataTemplateManager",initMethod="initialize")] public class RoleDataTemplateManager implements IResourceLoader { [Autowired] public var resourceManager:ResourceManager; public function initialize():void { resourceManager.register(this); } }注意注入进去的对象必须是public,否则注不进去。
对象读取:
var configManager:ConfigManager=context.getObject("configManager");2.3 如何注入第三方库中的对象
创建一个对象,比如AppConfig
[Configuration] public final class AppConfig { public var stageAutowireProcessor:DefaultAutowiringStageProcessor; public var eventHandlerMetadataProcessor:EventHandlerMetadataProcessor; public var routeEventsMetadataProcessor:RouteEventsMetaDataProcessor; }
Reference:
原文链接:http://blog.csdn.net/jiangguilong2000/article/details/9705479