class SpringFactoryInstance extends FactoryInstance { private Log log = LogFactory.getLog(getClass()); SpringFactoryInstance(FlexFactory factory, String id, ConfigMap properties) { super(factory, id, properties); } public Object lookup() { ApplicationContext appContext = WebApplicationContextUtils. getRequiredWebApplicationContext( FlexContext.getServletConfig().getServletContext() ); String beanName = getSource(); try { log.info("Lookup bean from Spring ApplicationContext: " + beanName); return appContext.getBean(beanName); } catch (NoSuchBeanDefinitionException nex) { ... } catch (BeansException bex) { ... } catch (Exception ex) { ... } } } |
FlexFactoryImpl 负责实例化 SpringFactoryInstance 并通过 SpringFactoryInstance 的 lookup()
方法查找 FlexService 接口对象:
public class FlexFactoryImpl implements FlexFactory { private Log log = LogFactory.getLog(getClass()); public FactoryInstance createFactoryInstance(String id, ConfigMap properties) { log.info("Create FactoryInstance."); SpringFactoryInstance instance = new SpringFactoryInstance(this, id, properties); instance.setSource(properties.getPropertyAsString(SOURCE, instance.getId())); return instance; } public Object lookup(FactoryInstance instanceInfo) { log.info("Lookup service object."); return instanceInfo.lookup(); } public void initialize(String id, ConfigMap configMap) { } } |
以下是 BlazeDS 查找 FlexService 接口的过程:
注意到 destination 的 id 并没有写死在代码中,而是通过以下语句获得的:
清单 11. 获取 destination 的 IDproperties.getPropertyAsString(SOURCE, instance.getId()) |
Property 的 SOURCE 属性由 BlazeDS 读取 XML 配置文件获得:
清单 12. 配置 destination 的 id<destination id="flexService"> <properties> <factory>flexFactory</factory> <source>flexService</source> <scope>application</scope> </properties> </destination> |
如果您没有使用 Spring 框架,也不要紧,只需修改 FactoryInstance 的 lookup() 方法。例如,对于一个 EJB 来说,lookup() 方法应该通过 JNDI 查找返回远程接口。无论应用程序结构如何,我们的最终目标是向 BlazeDS 返回一个 FlexService 的实例对象。
开发 Flex 客户端
首先安装 Flex Build