DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. An Introduction to Spring BlazeDS Integration

An Introduction to Spring BlazeDS Integration

Christophe Coenraets user avatar by
Christophe Coenraets
·
Apr. 02, 09 · Interview
Like (0)
Save
Tweet
Share
161.68K Views

Join the DZone community and get the full member experience.

Join For Free

Last December, SpringSource and Adobe announced a partnership aimed at streamlining the integration between Spring and BlazeDS. This partnership has led to the new Spring BlazeDS Integration project, which allows you to seamlessly integrate the two technologies and build state-of-the-art Internet applications that feature a Flex front end and a Spring back end.

Whether you are a Flex developer just learning Spring or a Spring developer learning Flex, you can benefit from the powerful integration of these technologies.

Spring has emerged as the de facto standard for building the Java back end of Internet applications. Flex is rapidly becoming the preferred technology for building innovative Internet applications delivered in the browser and on the desktop (using the Adobe AIR runtime).

This article provides an introduction to the Spring BlazeDS Integration, and includes a simple example application to illustrate key concepts.

What is Spring?

The foundation of the Spring framework is a lightweight component container that implements the Inversion of Control (IoC) pattern. Using an IoC container, components don't instantiate or even look up their dependencies (the objects they work with). The container is responsible for injecting those dependencies when it creates the components (hence the term "Dependency Injection", which is also used to describe this pattern).

By enabling looser coupling between components, the Spring IoC container has proven to be a solid foundation for building robust enterprise applications.

The components managed by the Spring IoC container are called Spring beans. In addition to its core IoC container, The Spring framework includes several other modules, including support for transaction management, JDBC Data Access, and ORM Data Access. While these modules are beyond the scope of this article, it is important to note that an additional benefit of using BlazeDS with Spring is the ability to leverage these modules to facilitate the development of your remote objects. More information on the Spring framework can be found here.

What is Flex?

Flex is an environment for building Rich Internet Applications. The Flex programming model includes:

  • ActionScript - an ECMAScript-compliant, object-oriented programming language. With some syntactical  differences, ActionScript looks and feels similar to Java, and supports the same object-oriented constructs: packages, classes, inheritance, interfaces, strong (but also dynamic) typing, and so on.
  • MXML - an XML-based language that provides an abstraction on top of ActionScript, and allows parts of an application (typically the View) to be built declaratively.
  • An extensive set of class libraries. The documentation is available here in Javadoc-like format.

The Flex source code (.mxml and .as files) is compiled into Flash bytecode (.swf) that is executed at the client side by the ActionScriptVirtual Machine in Flash Player using a Just-In-Time compiler.

The Flex SDK is an open-source project. It includes the Flex component library, the compiler, the debugger, and the documentation. A complete discussion of Flex is beyond the scope of this article, but you can find more information and download the Flex SDK here.

What is BlazeDS?

BlazeDS is a set of data services that give your Flex applications additional options for data connectivity. Without BlazeDS (or, without deploying any Flex-specific component on the server side), Flex applications can access back-end data using either the HTTPService or WebService components:

  • You use the HTTPService component to send HTTP requests to a server and consume the response. Although the HTTPService is often used to consume XML, it can be used to consume responses in other formats, including JSON. The Flex HTTPService is similar to the XMLHttpRequest component available in Ajax.
  • You use the WebService component to invoke SOAP-based web services.

       BlazeDS adds the following services:

  • The Remoting Service allows your Flex application to directly invoke methods of Java objects deployed in your application server.
  • The Message Service provides a publish/subscribe infrastructure that enables your Flex application to publish messages and subscribe to a messaging destination, enabling the development of real-time data push and collaborative applications. 
  • The Proxy Service allows your Flex application to make cross-domain service requests in a secure and controlled manner. In other words, it allows your Flex application to access a service available on a different domain than the domain from where the application was downloaded (without having to deploy a crossdomain.xml policy file on the target domain).

BlazeDS is deployed as a set of JAR files as part of your web application. Like the Flex SDK, BlazeDS is an open-source project. More information is available here.

Accessing Spring Beans from a Flex Application

If Flex clients can remotely access Java objects using BlazeDS, and if Spring beans are just regular Java objects, aren't you all set and ready to start accessing Spring beans from Flex clients? Almost…

By default, you configure BlazeDS remote objects in a configuration file called remoting-config.xml located in WEB-INF\flex. For example, to make a Java class named ProductService available remotely to a Flex application under the logical name “product”, you would define a destination as follows:

<destination id="product">
<properties>
<source>my.package.ProductService</source>
</properties>
</destination>


This destination allows a Flex application to invoke the public methods of ProductService. Here is a minimalist Flex application that populates a DataGrid with a list of products obtained by remotely invoking the findAll() method of the ProductService class.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">

<mx:RemoteObject id="ro" destination="productService"/>

<mx:DataGrid dataProvider="{ro.findAll.lastResult}" width="100%" height="100%"/>

<mx:Button label="Get Data" click="ro.findAll()"/>

</mx:Application>

 

The problem is that by default, BlazeDS takes care of instantiating and managing the life cycle of the remote objects defined in remoting-config.xml. The whole idea behind Spring IoC, however, is to let the container instantiate components (and inject their dependencies). The key to the integration of Spring and BlazeDS, therefore, is to find the best possible arrangement to leverage the data services provided by BlazeDS while letting the Spring container manage the configuration, instantiation, and life cycle of the remote objects.

The Old Approach: SpringFactory

BlazeDS provides a general purpose integration/pluggability mechanism based on the Factory pattern. You can plug a custom factory in the definition of a destination to delegate the instantiation and life cycle management of the underlying remote object to another subsystem. The role of the factory is to provide ready-to-use instances of objects to BlazeDS instead of letting BlazeDS instantiate those components. To create a factory, you create a class that implements the flex.messaging.FlexFactory interface, and you implement the lookup() method used by BlazeDS to obtain an instance of a remote object.  Internally, the lookup() method may construct a new instance, or obtain it from somewhere else.

Historically, Adobe has provided a SpringFactory class that provides BlazeDS with fully initialized (dependency-injected) instances of objects obtained from the Spring container.

Configuring a destination to delegate the instantiation of a remote object to Spring was a two step process.

1.    Register the Spring factory in WEB-INF/flex/services-config.xml:

<factories>
<factory id="spring" class="flex.samples.factories.SpringFactory"/>
</factories>


2.    Configure the destination to use the factory:

<destination id="myService">
<properties>
<factory>spring</factory>
<source>myBean</source>
</properties>
</destination>



Although it provides basic integration between BlazeDS and Spring, the factory approach has a number of shortcomings:

  • The “dependency lookup” approach described above is squarely at odds with the Spring “dependency injection” approach.
  • Objects have to be configured twice: once in the BlazeDS remoting-config.xml file and again in the Spring application context file.
  • The overall system configuration is spread over multiple files. BlazeDS is configured in web.xml, and remoting-config.xml, while Spring is configured in its own application context XML file.
  • The integration is limited to basic “remoting” and doesn’t cover other important aspects such as security and messaging.

The Spring BlazeDS Integration Project

The SpringSource and Adobe partnership is aimed at streamlining the integration between Spring and BlazeDS. This partnership has resulted in a new subproject in the Spring web portfolio: the Spring BlazeDS Integration project.

Instead of having two concurrent systems that have their own configuration approach and that communicate in a rudimentary way, the goal of the project was to let Spring manage BlazeDS “the Spring way”, just as it manages the other components of an application, and therefore provide a much deeper and cohesive level of integration between the two technologies.

The Spring BlazeDS Integration project is still a work in progress, but the currently available Milestone 2 build already fulfills that vision with the following features:

  1. The MessageBroker, which is the cornerstone of the BlazeDS engine, is configured and bootstrapped as a Spring-managed bean and doesn’t need to be configured in web.xml.
  2. Flex messages are routed to the MessageBroker through the Spring DispatcherServlet.
  3. Remote objects are configured the “Spring way” in the application context configuration file. You don’t need a remoting-config.xml file when working with BlazeDS and Spring.
  4. The Spring security integration ensures that you can secure Spring-managed beans exposed as remote objects just as you would secure any other Spring-managed endpoint, and that you can provide your security credentials from within a Flex application through the channelSet.login() API.

A Simple Example

To set up a simple Spring BlazeDS Integration application, you will need to:

  1. Configure Spring in web.xml.
  2. Configure the BlazeDS message broker as a Spring-managed bean in the application context configuration file.
  3. Configure your beans and expose them as remote objects in the application context configuration file.

Note: Depending on the DispatcherServlet mapping defined in web.xml, you may also need to adjust the default channel configuration in the BlazeDS services-config.xml file.

In web.xml, you configure the DispatcherServlet to bootstrap the Spring WebApplicationContext as usual. In this simple configuration, you then map all the /messagebroker requests to the DispatcherServlet.

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">

<servlet>
<servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/web-application-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
<url-pattern>/messagebroker/*</url-pattern>
</servlet-mapping>

</web-app>



In web-application-config.xml, you first configure the BlazeDS message broker as a Spring-managed bean using the simple message-broker tag. This will bootstrap the BlazeDS message broker. When you use the message-broker tag without mapping child elements, all incoming DispatcherServlet requests are mapped to the MessageBroker. You can add mapping child elements if you need more control.

With the message-broker in place, you then configure your Spring beans as usual, and you expose the beans you want to make available for remote access using the remote-service tag.

web-application-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:flex="http://www.springframework.org/schema/flex"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/flex
http://www.springframework.org/schema/flex/spring-flex-1.0.xsd">

<flex:message-broker/>

<bean id="productService" class="my.package.ProductDAO" >
<flex:remote-service />
<constructor-arg ref="dataSource"/>
</bean>

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.h2.Driver" />
<property name="url" value="jdbc:h2:~/sprinflexdemodb/sprinflexdemodb" />
</bean>

</beans>



The above configuration allows a Flex application to invoke the public methods of the productService bean. Here is a minimalist Flex application that populates a DataGrid with a list of products obtained by remotely invoking the findAll() method of the ProductService class.

Note that this is the same code that was used to connect to a plain BlazeDS installation: The client-side code is isolated from the specific server-side implementation.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">

<mx:RemoteObject id="ro" destination="productService"/>

<mx:DataGrid dataProvider="{ro.findAll.lastResult}" width="100%" height="100%"/>

<mx:Button label="Get Data" click="ro.findAll()"/>

</mx:Application>

 

Integrating Security

A full description of Spring security is outside the scope of this article. You can refer to the Spring documentation for more information. Here is a basic web.xml file configured to use Spring security:

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">

<display-name>Spring BlazeDS Integration Samples</display-name>

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/config/web-application-config.xml
/WEB-INF/config/web-application-security.xml
</param-value>
</context-param>

<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<servlet>
<servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
<url-pattern>/messagebroker/*</url-pattern>
</servlet-mapping>

<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>

</web-app>



For the purpose of this introduction, a basic authentication provider can be defined in web-application-security.xml as follows:

web-application-security.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-2.0.1.xsd">

<http auto-config="true" session-fixation-protection="none"/>

<authentication-provider>
<user-service>
<user name="john" password="john" authorities="ROLE_USER, ROLE_ADMIN" />
<user name="guest" password="guest" authorities="ROLE_GUEST" />
</user-service>
</authentication-provider>

</beans:beans>


In your web-application context, you can then set security as usual. The example below specifies that a user needs to be authenticated and belong to the ROLE_USER role to access the "find*" methods.

    <bean id="productService" class="flex.spring.samples.product.ProductDAO" >
<flex:remote-service/>
<constructor-arg ref="dataSource"/>
<security:intercept-methods>
<security:protect method="find*" access="ROLE_USER" />
</security:intercept-methods>
</bean>


If you now run the client application, you will get an Access Denied exception unless you have authenticated outside the Flex application.

The Spring security integration also allows you to authenticate from inside the Flex application using the standard channelSet.login() API. In the following version of the application, I added a simple user interface and the basic infrastructure to authenticate using the ChannelSet API.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
applicationComplete="applicationCompleteHandler()">

<mx:Script>
<![CDATA[

import mx.messaging.ChannelSet;
import mx.messaging.channels.AMFChannel;
import mx.controls.Alert;
import mx.rpc.events.FaultEvent;

private function applicationCompleteHandler():void
{
var channel:AMFChannel = new AMFChannel("my-amf", "http://localhost:8080/messagebroker/amf");
var channelSet:ChannelSet = new ChannelSet();
channelSet.addChannel(channel);
ro.channelSet = channelSet;
}

private function faultHandler(event:FaultEvent):void
{
Alert.show(event.fault.faultString, "Error accessing RemoteObject");
}

private function login():void
{
ro.channelSet.login(userId.text, password.text);
}

private function logout():void
{
ro.channelSet.logout();
}

]]>
</mx:Script>

<mx:RemoteObject id="ro" destination="productService" fault="faultHandler(event)"/>

<mx:Form>
<mx:FormItem label="User Id">
<mx:TextInput id="userId"/>
</mx:FormItem>
<mx:FormItem label="Password">
<mx:TextInput id="password" displayAsPassword="true"/>
</mx:FormItem>
<mx:FormItem direction="horizontal">
<mx:Button label="Login" click="login()"/>
<mx:Button label="Logout" click="logout()"/>
</mx:FormItem>
</mx:Form>

<mx:DataGrid dataProvider="{ro.findAll.lastResult}" width="100%" height="100%"/>

<mx:Button label="Get Data" click="ro.findAll()"/>

</mx:Application>

 

Status and Roadmap

The Spring  BlazeDS integration project is still a work in progress, but the Milestone 2 build that is currently available already provides very valuable features. The next milestone will provide integration with the BlazeDS Message Service. Integration with the data management services in LiveCycle Data Services ES is also on the roadmap.

Summary

The Spring BlazeDS Integration project enables you to seamlessly integrate Flex, BlazeDS, and Spring to build expressive, high-performance, and well-architected Rich Internet Applications. If you are already a Spring developer, you can leverage your existing infrastructure and simply expose your beans for remote access by Flex clients via BlazeDS remoting. If you are an existing Flex and BlazeDS developer, you can use Spring BlazeDS Integration to easily leverage the many powerful features of the Spring IoC container and other components of the Spring Framework.

Resources

  • The Spring BlazeDS Integration Project
  • BlazeDS Open Source Project
  • Flex SDK Open Source Project
  • Flex Builder Eclipse Plugin
  • Test Drive - The examples discussed in this article are based on “the Spring BlazeDS Test Drive” I created to help developers get started with the integration. The Test Drive consists of a minimal version of Tomcat with BlazeDS and the “Spring / BlazeDS integration” preconfigured and ready to use. It also includes a series of samples running “out-of-the-box”.

 

Spring Framework Integration application FLEX (protocol) Spring Security Object (computer science) Open source Message broker Web Service

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • How To Set Up and Run Cypress Test Cases in CI/CD TeamCity
  • Unlock the Power of Terragrunt’s Hierarchy
  • Important Data Structures and Algorithms for Data Engineers
  • 5 Common Firewall Misconfigurations and How to Address Them

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: