spring

  • submit to reddit

Getting Started with Spring-DM

By Craig Walls

16,698 Downloads · Refcard 57 of 151 (see them all)

Download
FREE PDF


The Essential Spring-DM Cheat Sheet

Spring is a framework that promotes development of loosely coupled/highly cohesive objects through dependency injection and interface-oriented design. Spring Dynamic Modules (Spring-DM) brings Spring and OSGi together to enable a declarative service model for OSGi that leverages Spring’s power of dependency injection. This DZone Refcard shows you how to use Spring-DM to wire together OSGi services to build highly modular and dynamic applications. You may also enjoy the other Spring DZone Refcardz in our Collection: Spring Configuration and Spring Annotations.
HTML Preview
Getting Started with Spring-DM

Getting Started with Spring-DM

By Craig Walls

about spring-dm

Spring is a framework that promotes development of looselycoupled/ highly-cohesive objects through dependency injection and interface-oriented design. OSGi is a framework specification that promotes development of loosely-coupled/ highly-cohesive application modules through services and interface-oriented design. Seems like a match made in heaven! Spring Dynamic Modules (Spring-DM) brings Spring and OSGi together to enable a declarative service model for OSGi that leverages Spring’s power of dependency injection. This reference card will be your resource for working with Spring- DM to wire together OSGi services and ultimately building modular applications.

You may be interested to know that Spring-DM is the basis for the SpringSource dm Server, a next-generation application server that embraces modularity through OSGi. What’s more, the upcoming OSGi R4.2 specification includes a component model known as the OSGi Blueprint Services that is heavily influenced by Spring-DM.

Introducing Spring-DM

The star player of Spring-DM is a bundle known as the Spring- DM extender. The Spring-DM extender watches for bundles to be installed and inspects them to see if they are Springenabled (that is, if they contain a Spring application context definition file). When it finds a Spring-enabled bundle, the extender will create a Spring application context for the bundle.

Spring Application Contexts

Spring-DM also provides a Spring configuration namespace that enables you to declare and publish Spring beans as OSGi services and to consume OSGi services as if they were just beans in a Spring application context. This declarative model effectively eliminates the need to work with the OSGi API directly.

Installing Spring-DM

One of the nice things about Spring-DM is that you do not need to include it in the classpath of your OSGi bundles or even reference it from those bundles. Installing Spring-DM involves two parts:

  1. Installing the Spring-DM and supporting bundles in your OSGi framework
  2. Adding the Spring-DM configuration namespace to your bundle’s Spring configuration XML files

You can download Spring-DM from
http://www.springframework.org/osgi. The distribution comes complete with everything you need to work with Spring- DM, including the Spring-DM extender bundle and all of its dependency bundles.

Installing the Spring-DM extender bundles

There are several means by which you can install bundles into an OSGi framework, depending on the OSGi framework and any add-ons or tools you may be using. But the most basic way is to use the “install” command that is available in most OSGi framework shells. For example, to install the Spring- DM extender bundle and the supporting Spring-DM bundles (assuming that you’ve unzipped the Spring-DM distribution in / spring-dm-1.2.0):


osgi> install file:///spring-dm-1.2.0/dist/spring-osgi-core-
   1.2.0.jar
osgi> install file:///spring-dm-1.2.0/dist/spring-osgi-extender-
   1.2.0.jar
osgi> install file:///spring-dm-1.2.0/dist/spring-osgi-io-
   1.2.0.jar

Spring-DM depends on the Spring framework, so you’ll also need to install several other Spring bundles:

refcardzad


osgi> install file:///spring-dm-1.2.0/lib/spring-aop-2.5.6.A.jar
osgi> install file:///spring-dm-1.2.0/lib/spring-context-
    2.5.6.A.jar
osgi> install file:///spring-dm-1.2.0/lib/spring-core-2.5.6.A.jar
osgi> install file:///spring-dm-1.2.0/lib/spring-beans-2.5.6.A.jar

Finally, you’ll also need to install several other supporting bundles that Spring and Spring-DM depend on:


osgi> install file:///spring-dm-1.2.0/lib/com.springsource.net.
   sf.cglib-2.1.3.jar
osgi> install file:///spring-dm-1.2.0/lib/com.springsource.org.
   aopalliance-1.0.0.jar
osgi> install file:///spring-dm-1.2.0/lib/com.springsource.slf4j.
   api-1.5.0.jar
osgi> install file:///spring-dm-1.2.0/lib/com.springsource.slf4j.
   log4j-1.5.0.jar
osgi> install file:///spring-dm-1.2.0/lib/com.springsource.slf4j.
   org.apache.commons.logging-1.5.0.jar
osgi> install file:///spring-dm-1.2.0/lib/log4j.osgi-1.2.15-
   SNAPSHOT.jar

Hot Tip

Use tools to help install bundles Installing bundles using the “install” command should work with almost any OSGi framework, but it is also quite a manual process. Pax Runner (http:// paxrunner.ops4j.org) is an OSGi framework launcher that takes a lot of the tedium out of installing bundles. Just use Pax Runner’s “spring dm” profile: % pax-run.sh --profiles=spring.dm

The Spring-DM configuration namespace

Schema URI:

http://www.springframework.org/schema/osgi

Schema XSD:

http://www.springframework.org/schema/osgi/spring-osgi.xsd

When it comes to declaring services and service consumers in Spring-DM, you’ll use Spring-DM’s core namespace. To do that, you’ll need to include the namespace in the XML file.


<?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:osgi=”http://www.springframework.org/schema/osgi”
	xsi:schemaLocation=”http://www.springframework.org/
schema/beans
	    http://www.springframework.org/schema/beans/
spring-beans.xsd
		   http://www.springframework.org/schema/osgi
		     http://www.springframework.org/schema/
osgi/spring-osgi.xsd”>
...
</beans>

Spring’s “beans” namespace is the default namespace, but if you know that most or all of the elements in the Spring configuration file will be from the Spring-DM namespace, you can make it the default namespace:

spring beans

Publishing Services

To demonstrate Spring-DM’s capabilities, we’re going to create a few OSGi services that translate English text into some other language. All of these services will implement the following Translator interface:


package com.habuma.translator;
public interface Translator
   {
String translate(String text);
}

The first service we’ll work with is one that translates English into Pig Latin. It’s implementation looks something like this:


package com.habuma.translator.piglatin;
import com.habuma.translator.Translator;
public class PigLatinTranslator implements Translator {
	private final String VOWELS = “AEIOUaeiou”;
	public String translate(String text) {
	  // actual implementation left out for brevity
	}
}

If we were working with basic OSGi (that is, without Spring- DM), we’d publish this service to the OSGi service registry using the OSGi API, perhaps in a bundle activator’s start() method:


public void start(BundleContext context) throws Exception {
	context.registerService(Translator.class.getName(),
				new PigLatinTranslator(), null);
}

Although the native OSGi approach will work fine, it requires us to work programmatically with the OSGi API. Instead, we’ll publish services declaratively using Spring-DM. The first step: Create a Spring context definition file that declares the PigLatinTranslator as a Spring bean:


<?xml version=”1.0” encoding=”UTF-8”?>
<beans xmlns=”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/springbeans.
xsd”>
  <bean id=”pigLatinTranslator”
    class=”com.habuma.translator.piglatin.PigLatinTranslator” />
</beans>

Hot Tip

Overriding the context configuration location By default, the Spring-DM extender looks for all XML files located in a bundle’s META-INF/spring folder and assumes that they’re all Spring context definition files that are to be used to create a Spring application context for the bundle; however, if you’d like to put your context definition files elsewhere in the bundle, use the Spring-Context: header in the META-INF/ MANIFEST.MF file.
For example, if you’d rather place your Spring configuration files in a directory called “spring-config” at the root of the bundle, add the following entry to your bundle’s manifest: Spring-Context: spring-config/*.xml

This Spring context file can be named anything, but it should be placed in the Pig Latin translator bundle’s META-INF/ spring directory. When the bundle is started in an OSGi framework, the Spring-DM extender will look for Spring context configuration files in that directory and use them to create a Spring application context for the bundle.

Publishing a simple OSGi service

By itself the Spring context we’ve created only creates a bean in the Spring application context. It’s not yet an OSGi service. To publish it as an OSGi service, we’ll create another Spring context definition file that uses the Spring-DM namespace:


<<?xml version=”1.0” encoding=”UTF-8”?>
<<beans:beans xmlns:beans=”http://www.springframework.org/schema/
beans”
		xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
		xmlns=”http://www.springframework.org/schema/osgi”
		xsi:schemaLocation=”http://www.springframework.org/
schema/beans
			http://www.springframework.org/schema/beans/
spring-beans.xsd
			  http://www.springframework.org/schema/osgi
				http://www.springframework.org/schema/
osgi/spring-osgi.xsd”>
   <<service ref=”pigLatinTranslator”
	  interface=”com.habuma.translator.Translator” />
<</beans:beans>

Hot Tip

Don’t mix your Spring and OSGi contexts Although you can certainly define all of your bundle’s Spring beans and OSGi services in a single Spring context definition file, it’s best to keep them in separate files (all in META-INF/spring). By keeping the OSGi-specific declarations out of the normal Spring context definition, you’ll be able to use the OSGi-free context to do non-OSGi integration tests of your beans.

This new Spring context file uses Spring-DM’s element to publish the bean whose ID is “pigLatinTranslator” in the OSGi service registry. The ref attribute refers to the Spring bean in the other context definition file. The interface attribute identifies the interface under which the service will be available in the OSGi service registry.

Publishing a service under multiple interfaces

Let’s suppose that the PigLatinTranslator class were to implement another interface, perhaps one called TextProcessor. And let’s say that we want to publish the service under both the Translator interface and the TextProcessor interface. In that case, you can use the element to identify the interfaces for the service:


<service ref=”pigLatinTranslator”>
  <interfaces>
    <beans:value>com.habuma.translator.Translator</beans:value>
    <beans:value>com.habuma.text.TextProcessor</beans:value>
  </interfaces>
</service>

Auto-selecting service interfaces

Instead of explicitly specifying the interfaces for a service, you can also let Spring-DM figure out which interfaces to use by specifying the auto-export attribute:


<service ref=”pigLatinTranslator”
       auto-export=”interfaces” />

By setting auto-export to “interfaces”, it tells Spring-DM to publish the service under all interfaces that the implementation class implements. You can also set auto-export to “all-classes” to publish the service under all interfaces and classes for the service or “class-hierarchy.”

Publishing a service with properties

It’s also possible to publish a service with properties to qualify that service. These properties can later be used to help refine the selection of services available to a consumer. For example, let’s say that we want to qualify Translator services by the language that they translate to:


<rvice ref=”pigLatinTranslator”
      interface=”com.habuma.translator.Translator”>
<service-properties>
   <beans:entry key=”translator.language” value=”Pig Latin” />
 </service-properties>
</service>

The <service-properties> element can contain one or more <entry> elements from the “beans” namespace. In this case, we’ve added a property named “translator.language” with a value of “Pig Latin”. Later, we’ll use this property to help select this particular service from among a selection of services that all implement Translator.

Consuming Services

Now that we’ve seen how to publish a service in the OSGi service registry, let’s look at how we can use Spring-DM to consume that service. To get started, we’ll create a simple client class:


package com.habuma.translator.client;
import java.util.List;
import com.habuma.translator.Translator;
public class TranslatorClient {
  private static String TEXT = “Be very very quiet. I’m hunting
rabbits!”;
  public void go() {
     System.out.println(“ TRANSLATED: “ +
        translator.translate(TEXT));
  }
  private Translator translator;
  public void setTranslator(Translator translator) {
    this.translator = translator;
  }
}

TranslatorClient is a simple POJO that is injected with a Translator and uses that Translator in its go() method to translate some text. We’ll declare it as a Spring bean like this:


<?xml version=”1.0” encoding=”UTF-8”?>
		<beans xmlns=”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/springbeans.
xsd”>
  <bean class=”com.habuma.translator.client.TranslatorClient”
     init-method=”go”>
   <property name=”translator” ref=”translator” />
  </bean>
</beans>

As with the service’s Spring context declaration, the name of this Spring context definition can be named anything, but it should be placed in the client bundle’s META-INF/spring folder so that the Spring-DM extender will find it.

The bean is declared with the init-method attribute set to call the go() method when the bean is created. And we use the <property> element to inject the bean’s translator property with a reference to a bean whose ID is “translator”.

The big question here is: Where does the “translator” bean come from?

Simple service consumption

Spring-DM’s <reference> element mirrors the <service> element. Rather than publishing a service, however, <reference> retrieves a service from the OSGi service registry. The simplest way to consume a Translator service is as follows:


<reference id=”translator”
interface=”com.habuma.translator.Translator” />

When the Spring-DM extender creates a Spring context for the client bundle, it will create a bean with an ID of “translator” that is a proxy to the service it finds in the service registry. With that id attribute and interface, it is quite suitable for wiring into the client bean’s translator property.

Setting a service timeout

In a dynamic environment like OSGi, services can come and go. When the client bundle starts up, there may not be a Translator service available for consumption. If it’s not available, then Spring-DM will wait up to 5 minutes for the service to become available before giving up and throwing an exception.

But it’s possible to override the default timeout using the <reference> element’s timeout attribute. For example, to set the timeout to 1 minute instead of 5 minutes:


<reference id=”translator”
	interface=”com.habuma.translator.Translator”
	timeout=”60000” />

Notice that the timeout attribute is specified in milliseconds, so 60000 indicates 60 seconds or 1 minute.

Optional service references

Another way to deal with the dynamic nature of OSGi services is to specify that a service reference is optional. By default, the cardinality of a reference to a service is “1..1”, meaning that the service must be found within the timeout period or else an exception will be thrown. But you can specify an optional reference by setting the cardinality to “0..1”:


<reference id=”translator”
	interface=”com.habuma.translator.Translator”
	cardinality=”0..1” />

Filtering services

Imagine that we have two or more Translator services published in the OSGi service registry. Let’s say that in addition to the Pig Latin translator there’s also another Translator service that translates text into Elmer Fudd speak. How can we ensure that our client gets the Pig Latin service when another implementations may be available?

Earlier, we saw how to set a property on a service when it’s published. Now we’ll use that property to filter the selection of services found on the consumer side:


<reference id=”translator”
	interface=”com.habuma.translator.Translator”
	filter=”(translator.language=Pig Latin)” />

The filter attribute lets us specify properties that will help refine the selection of matching services. In this case, we’re only interested in a service that has its “translator.language” property set to “Pig Latin”.

Consuming multiple services

But why choose? What if we wanted to consume all matching services? Instead of pin-pointing a specific service, we can use Spring-DM’s <list> element to consume a collection of matching services:


<list id=”translators”
	interface=”com.habuma.translator.Translator” />

The Spring-DM extender will create a list of matching services that can be injected into a client bean collection property such as this one:


private List<Translator> translators;
public void setTranslators(List<Translator> translators) {
  this.translators = translators;
}

Optionally, you can use Spring-DM’s <set> element to create a set of matching services:


<set id=”translators”
   interface=”com.habuma.translator.Translator” />

The <list> and <set> elements share many of the same attributes with <reference>. For example, to consume a set of all Translator services filtered by a specific property:


<set id=”translators”
interface=”com.habuma.translator.Translator”
filter=”(translator.language=Elmer Fudd)” />

Testing Bundles

Hopefully, you’re in the habit of writing unit tests for your code. If so, that practice should extend to the code that is contained within your OSGi bundles. Because Spring-DM encourages POJO-based OSGi development, you can continue to write unit-tests for the classes that define and consume OSGi services just like you would for any other non-OSGi code.

But it’s also important to write tests that exercise your OSGi services as they’ll be used when deployed in an OSGi container. To accommodate in-OSGi integration testing of bundles, Spring-DM provides AbstractConfigurableBundleCreatorTests, a JUnit 3 base test class from which you can write your bundle tests.

What’s fascinating is how tests based on AbstractConfigurableBundleCreatorTests work. When the test is run, it starts up an OSGi framework implementation (Equinox by default) and installs one or more bundles into the framework. Finally, it wraps itself in an on-the-fly bundle and installs itself into the OSGi framework so that it can test bundles as an insider.

Writing a basic OSGi test

To illustrate, let’s write a simple test that loads our Translator interface bundle and the Pig Latin implementation bundle:


package com.habuma.translator.test;
import org.osgi.framework.ServiceReference;
import org.springframework.osgi.test.
AbstractConfigurableBundleCreatorTests;


import com.habuma.translator.Translator;
public class PigLatinTranslatorBundleTest
      extends AbstractConfigurableBundleCreatorTests {
  @Override
  protected String[] getTestBundlesNames() {
     return new String[] {
		“com.habuma.translator, interface, 1.0.0”,
		“com.habuma.translator, pig-latin, 1.0.0”
      };
  }
  public void testOsgiPlatformStarts() {
    assertNotNull(bundleContext);
  }
}

The getTestBundleNames() method returns an array of Strings where each entry represents a bundle that should be installed into the OSGi framework for the test. The format of each entry is a comma-separated set of values that identify the bundle by its Maven group ID, artifact ID, and version number.

So far, our test has a single test method, testOsgiPlatformStarts(). All this method does is test that the OSGi framework has started by asserting that bundleContext (inherited from AbstractConfigurableBundleCreatorTests) is not null.

Testing OSGi service references

A more interesting test we could write is one that uses the bundle context to lookup a reference to the Translator service and assert that it meets our expectations:


public void testServiceReferenceExists() {
  ServiceReference serviceReference =
    bundleContext.getServiceReference(Translator.class.
getName());
	assertNotNull(serviceReference);
	assertEquals(“Pig Latin”,
       serviceReference.getProperty(“translator.language”));
}

Here we retrieve a ServiceReference from the bundle context and assert that it isn’t null. This means that some implementation of the Translator service has been published in the OSGi service registry. Then, it examines the properties of the service reference and asserts that the “translator.language” property has been set to “Pig Latin”, as we’d expect from how we published the service earlier.

Testing OSGi services

One more thing we could test is that the Translator service does what we’d expect it to do. Certainly, this kind of test usually belongs in a unit test. But it’s still good to throw a smoke test its way to make sure that we’re getting the service we’re expecting.

We could use the ServiceReference to lookup the service. But, we can avoid any additional work with the OSGi API by having the Translator service wired directly into our test class. First, let’s add a Translator property and setter method to our test class


private Translator translator;
public void setTranslator(Translator translator) {
  this.translator = translator;
}

When the test is run, Spring will attempt to autowire the property with a bean from its own Spring application context. But we haven’t defined a Spring application context for the test yet. Let’s do that now:


<?xml version=”1.0” encoding=”UTF-8”?>
<beans:beans xmlns:beans=”http://www.springframework.org/schema/
beans”
		xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
		xmlns=”http://www.springframework.org/schema/osgi”
   xsi:schemaLocation=”http://www.springframework.org/schema/
beans
      http://www.springframework.org/schema/beans/spring-beans.
xsd
    http://www.springframework.org/schema/osgi
    http://www.springframework.org/schema/osgi/spring-osgi.xsd”>
  <reference id=”translator”
    interface=”com.habuma.translator.Translator” />
</beans:beans>

You’ll recognize that this Spring context definition looks a lot like the one we created for the service consumer. In fact, our test class will ultimately be a consumer of the Translator service. We just have one more thing to do before we can test the service—we’ll need to override the getConfigLocations() method to tell the test where it can find the context definition file:


@Override
protected String[] getConfigLocations() {
   return new String[] { “bundle-test-context.xml” };
}

Now we can write our test method:


public void testTranslatorService() {
	assertNotNull(translator);
	assertEquals(“id-DAY is-thAY ork-wAY”,
       translator.translate(“Did this work”));
}

This method assumes that by the time it is invoked, the translator property has been set. It first asserts that it is not null and then throws a simple test String at it to test that the service does what we expect.

Changing the tested OSGi framework

By default, Spring-DM tests are run within Equinox. But you can change them to run within another OSGi framework implementation such as Apache Felix or Knopflerfish by overriding the getConfigLocations() method. For example, to run the test within Apache Felix:


@Override
  protected String getPlatformName() {
    return Platforms.FELIX;
}

Or for Knoplerfish:


@Override
protected String getPlatformName() {
  return Platforms.KNOPFLERFISH;
}

Providing a Custom Manifest

When a Spring-DM test gets wrapped up in an on-the-fly bundle, a manifest will be automatically generated for it. But if you’d like to provide a custom manifest. To provide a custom manifest for the on-the-fly bundle, all you need to do is override the getManifestLocation(). For example:


protected String getManifestLocation() {
  return “classpath:com.habuma.translator.Translator.MF”;
}

Be aware, however, that if you provide a custom manifest, you must include a few things in that manifest to make Spring-DM testing work. First, you’ll need to specify a bundle activator:


Bundle-Activator: org.springframework.osgi.test.JUnitTestActivator

And you’ll need to import JUnit and Spring-DM packages:


Import-Package: junit.framework,
  org.osgi.framework,
  org.apache.commons.logging,
  org.springframework.util,
  org.springframework.osgi.service,
  org.springframework.osgi.util,
  org.springframework.osgi.test,
  org.springframework.context

References

Example Source Code:

http://www.habuma.com/refcard/spring-dm/translator.zip

Spring-DM Homepage:

http://www.springframework.org/osgi

OSGi Alliance:

http://www.osgi.org

Modular Java on Twitter:

http://twitter.com/modularjava

Craig’s Modular Java Blog:

http://www.modularjava.com

Craig’s Spring Blog:

http://www.springinaction.com

56 76

About The Author

Photo of Craig Walls

Craig Walls

is a Texas-based software developer with more than 15 years experience working the telecommunication, financial, retail, education, and software industries. He’s a zealous promoter of the Spring Framework, speaking frequently at local user groups and conferences and writing about Spring and OSGi on his blog. When he’s not slinging code, Craig spends as much time as he can with his wife, two daughters, six birds, and two dogs.

Craig’s Publications:

  • Modular Java: Creating Flexible Applications with OSGi and Spring, 2009
  • Spring in Action, 2nd Edition, 2007
  • XDoclet in Action, 2003

Craig’s Blog: http://www.springinaction.com

Recommended Book

Spring in action

Newcomers will find a thorough introduction to the framework, while experienced Drupal developers will learn best practices for building powerful websites. With Using Drupal, you’ll find concrete and creative solutions for developing the exact community website you have in mind.


Recommended Book

ModularJava

Modular Java is filled with tips and tricks that will make you a more proficient OSGi and Spring-DM developer. Equipped with the know-how gained from this book, you’ll be able to develop applications that are more robust and agile.

Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


Your download should begin immediately.
If it doesn't, click here.

Flex & Spring Integration

By Jon Rose and James Ward

14,378 Downloads · Refcard 48 of 151 (see them all)

Download
FREE PDF


The Essential Flex & Spring Integration Cheat Sheet

Adobe Flex Software is a popular framework for building Rich Internet Applications (RIAs). The Flex framework is used to create SWF files that run inside Flash Player. This DZone Refcard shows you how to integrate Flex and Spring to create a powerful platform for building robust RIAs. It starts off by showing you how to set up a server-side Java project with BlazeDS and the Spring Framework. After configuring your project with a basic Spring bean for use in BlazeDS, you’ll write your Flex application to use the Spring/BlazeDS service.
HTML Preview
Flex & Spring Integration

Flex & Spring Integration

By Jon Rose and James Ward

ABOUT Adobe Flex

Adobe Flex Software is a popular framework for building Rich Internet Applications (RIAs). The Flex framework is used to create SWF files that run inside Flash® Player. The framework was built for use by developers and follows traditional application development paradigms rather than the timelinebased development found in the Flash Professional authoring tools. Applications are built using the Flex Builder IDE™ - an Eclipse-based development environment. ActionScript® 3 is used to access data and build user interface components for web and desktop applications that run inside Flash Player or Adobe AIR® Software. The Flex Framework also uses a declarative XML language called MXML to simplify Flex development and layout.

ABOUT Spring

The Spring Framework is one of the most popular ways to build enterprise Java applications. Unlike traditional Java EE development, Spring provides developers a full featured “lightweight container,” that makes applications easy to test and develop. Although Spring is best known for its dependency injection features, it also provides features for implementing typical server-side enterprise applications, such as declarative security and transaction management.

WHy Flex and Spring?

Adobe Flex has strong ties to Java, which include an Eclipsebased IDE and BlazeDS, its open source server-based Java remoting and web messaging technology. In addition, most enterprise projects that use Flex build on a Java back end. With Flex and Java so often married together, it is only natural to want to integrate Flex with Spring-based Java back ends. Beyond greenfield development, many organizations want to revamp or replace the user interface of existing enterprise Spring applications using Flex. In late 2008, the Spring community recognized these cases and began working on the Spring BlazeDS Integration project to add support for Flex development with Java and Spring.

By default BlazeDS creates instances of server-side Java objects and uses them to fulfill remote object requests. This approach doesn’t work with Spring, as the framework is built around injecting the service beans through the Spring container. The Spring integration with BlazeDS allows you to configure Spring beans as BlazeDS destinations for use as remote objects in Flex.

Integrating Flex and spring

This Refcard assumes that you are already familiar with Spring and Flex. If you need an introduction or refresher to either, check out the Very First Steps in Flex and/or Spring Configuration DZone Refcardz.

To use BlazeDS, the server-side application could be any Java application that deploys as a WAR file. This Refcard uses the Eclipse IDE to create and edit the Java project. This Refcard walks you through the following steps:

  • Set up a server-side Java project with BlazeDS and the Spring Framework
  • Configure the Java project with a basic Spring bean for use in BlazeDS
  • Write Flex application to use the Spring/BlazeDS service

Hot Tip

BlazeDS provides simple two-way communication with Java back-ends. Adobe Flash Player supports a serialization protocol called AMF that alleviates the bottlenecks of text-based protocols and provides a simpler way to communicate with servers. AMF is a binary protocol for exchanging data that can be used over HTTP in place of text-based protocols that transmit XML. Applications using AMF can eliminate an unnecessary data abstraction layer and communicate more efficiently with servers. To see a demonstration of the performance advantages of AMF, see the Census RIA Benchmark at: http://www.jamesward.org/census.The specification for AMF is publicly available, and numerous implementations of AMF exist in a variety of technologies including Java, .Net, PHP, Python, and Ruby.

Hot Tip

The open source BlazeDS project includes a Java implementation of AMF that is used for remotely communicating with server-side Java objects as well as for a publish/subscribe messaging system. The BlazeDS remoting technology allows developers to easily call methods on Plain Old Java Objects (POJOs), Spring services, or EJBs. Developers can use the messaging system to send messages from the client to the server, or from the server to the client. BlazeDS can also be linked to other messaging systems such as JMS or ActiveMQ. Because the remoting and messaging technologies use AMF over HTTP, they gain the performance benefits of AMF as well as the simplicity of fewer data abstraction layers. BlazeDS works with a wide range of Javabased application servers, including Tomcat, WebSphere, WebLogic, JBoss, and ColdFusion.

To follow along with this tutorial you will need:

First, set up the server-side Java web project in Eclipse by creating a web application from the blazeds.war file (found inside the blazeds zip file).

  • Import the Blazeds.war file to create the project:
    • Choose File > Import
    • Select the WAR file option. Specify the location of the blazeds.war file. For the name of the web project, type dzone-server
    • Click Finish

Now you can create a server that will run the application:

  • Select File > New > Other
  • Select Server > Server
  • Click Next
  • Select Apache > Tomcat v6.0Server
  • Click Next
  • Specify the location where Tomcat is installed and select the JRE (version 5 or higher) to use
  • Click Next
  • Select dzone-server in the Available Projects list
  • Click Add to add it to the Configured Projects list
  • Click Finish

Next, in the dzone-server project create the basic Java classes to be used by BlazeDS and Spring:


public class MyEntity {
  private String firstName;
  private String lastName;
  private String emailAddress;
  public String getFirstName() {
   return firstName;
  }
public void setFirstName(String firstName) {
  this.firstName = firstName;
  }
public String getLastName() {
  return lastName;
  }
public void setLastName(String lastName) {
  this.lastName = lastName;
  }
public String getEmailAddress() {
  return emailAddress;
  }
public void setEmailAddress(String emailAddress) {
  this.emailAddress = emailAddress;
  }
}

Listing 1: Java entity to be passed between Java and Flex


import java.util.List;
public interface MyService {
  public List<MyEntity> getMyEntities();
}

Listing 2: Java Service Interface


import java.util.ArrayList;
import java.util.List;
public class MyServiceImpl implements MyService {
  public List<MyEntity> getMyEntities() {
   List<MyEntity> list = new ArrayList<MyEntity>();
   MyEntity entity = new MyEntity();
   entity.setFirstName(“Hello”);
   entity.setLastName(“World”);
   entity.setEmailAddress(“hello@world.com”);
   list.add(entity);
   MyEntity entity2 = new MyEntity();
   entity2.setFirstName(“Hello”);
   entity2.setLastName(“Space”);
   entity2.setEmailAddress(“hello@space.com”);
   list.add(entity2);
   MyEntity entity3 = new MyEntity();
   entity3.setFirstName(“Hello”);
   entity3.setLastName(“Neighbor”);
   entity3.setEmailAddress(“hello@neighbor.com”);
   list.add(entity3);
   return list;
  }
}

Listing 3: Java Example Service Implementation

Listings 1, 2, and 3 are very basic Java classes that you’ll use as examples for this tutorial. In a real-world application, the service implementation would likely connect to one or more enterprise services for data, such as a relational database. In this case, it simply returns a hard-coded set of entities as an ArrayList.

The basic Java web project with the BlazeDS dependencies is now complete.

Next, configure the Java project with a basic Spring bean for the MyService interface:

  • Copy the Spring libraries, the Spring BlazeDS Integration Library, and the ANTLR library to the project dzoneserver/ WebContent/WEB-INF/lib directory
  • Create a basic Spring Configuration File:
    • Right Click WebContent/WEB-INF and then choose New > File
    • For the file name, type application-config.xml
    • Click Finish
    • Copy and paste the text from Listing 4 into the file

<?xml version=”1.0” encoding=”UTF-8”?>
 <beans xmlns=”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.5.xsd”>
 <!-- Spring Beans’s -->
 <bean id=”myService” class=”MyServiceImpl” />
</beans>

Listing 4: Basic Spring Configuration

Those familiar with Spring should recognize this as a basic Spring configuration for creating a simple bean from the MyServiceImpl class. Later in this tutorial you will be using this bean through BlazeDS.

At this point, you have a basic Java web project with a default BlazeDS configuration. Now, you’ll change the default BlazeDS configuration to use the newly created Spring bean.

To begin configuring Spring BlazeDS Integration, update the web.xml file by removing the default BlazeDS configuration and replacing it with the code from Listing 5.


<>?xml version=”1.0” encoding=”UTF-8”?>
<>web-app>
 <>display-name>dzone-server<>/display-name>
 <>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/application-config.xml<>/param-value>
   <>/init-param>
   <>load-on-startup>1<>/load-on-startup>
  <>/servlet>
  <>!-- Map /spring/* requests to the DispatcherServlet -->
  <>servlet-mapping>
   <>servlet-name>Spring MVC Dispatcher Servlet<>/servlet-name>
   <>url-pattern>/spring/*<>/url-pattern>
  <>/servlet-mapping>
<>/web-app>

Listing 5: web.xml

The web.xml contents in Listing 5 create a servlet filter from Spring that will process all BlazeDS requests at: http://localhost:8080/dzone-server/spring This will be the base URL for accessing the BlazeDS endpoint. Also, you should notice that this is a standard DispatcherServlet for Spring.

Now that you have Spring wired into the Java web application, you will update the basic Spring configuration from Listing 4 so that it will work with BlazeDS. Add the highlighted section from Listing 6 to your application-config.xml file.


<?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:flex=”http://www.springframework.org/schema/flex”
 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”>
 <!-- Spring Beans’s -->
 <bean id=”myService” class=”MyServiceImpl” />
 <!-- Simplest possible message broker -->
 <flex:message-broker />


 <!-- exposes myService as BlazeDS destination -->
 <flex:remote-service ref=”myService” />
</beans>

Listing 6: Advanced Spring Configuration for BlazeDS

Listing 6 exposes the MyServiceImpl class as a BlazeDS destination. First, the Flex® namespace is added to the configuration. Note that the XSD will not be published from Spring until the final 1.0 release, and until then you will have to add it manually to your XML catalog. With the Flex namespace added, the configuration uses the messagebroker tag to create the MessageBrokerFactoryBean. Since there is no additional configuration information provided, the MessageBroker will be created with “sensible defaults,” assuming that the service-config.xml is in WEB-INF/flex/ services-config.xml. The remote-service tag creates a destination from existing Spring beans.

Hot Tip

In Spring BlazeDS Integration release 1.0.0M2, the standard BlazeDS configuration file (servicesconfig. xml) is still used for configuration of the communication channels.

Next, update the default BlazeDS services-config.xml file (found in the WebContent/WEB-INF/flex folder) to reflect the Spring URL defined in the web.xml file. Replace the contents of the file with the code in Listing 7.


<?xml version=”1.0” encoding=”UTF-8”?>
  <services-config>
   <services>
    <default-channels>
     <channel ref=”my-amf”/>
   </default-channels>
  </services>
 <channels>
<channel-definition id=”my-amf”
class=”mx.messaging.channels.AMFChannel”>
  <endpoint
   url=”http://{server.name}:{server.port}/{context.root}/spring/
    messagebroker/amf”
   class=”flex.messaging.endpoints.AMFEndpoint”/>
  </channel-definition>
 <channel-definition id=”my-polling-amf”
class=”mx.messaging.channels.AMFChannel”>
<endpoint
  url=”http://{server.name}:{server.port}/{context.root}/spring/
   messagebroker/amfpolling”
    class=”flex.messaging.endpoints.AMFEndpoint”/>
     <properties>
    <polling-enabled>true</polling-enabled>
  <polling-interval-seconds>4</polling-interval-seconds>
 </properties>
</channel-definition>
</channels>
</services-config>

Listing 7: Update channel definition in services-config.xml

Note that the endpoint URL for the my-amf and my-polling-amf channels in Listing 7 include “spring” after the context.root parameter. This is the only configuration change you need to make in the BlazeDS default configuration files. All the remote destinations are configured in the Spring application-config. xml file.

You are now done configuring the server-side Spring / BlazeDS Java application. You may want to start up the Tomcat server to verify that your configuration is correct.

Now you can build the Flex application to use the Spring service remotely. Follow these steps to create the Flex project:

  • Select File > New > Other
  • In the Select A Wizard dialog box, select Flex Project
  • In the New Flex Project box, type in a project name: dzone-flex
  • Use the default location (which will already be checked)
  • Select Web Application (Runs In Flash Player)
  • Select None as the Application Server Type
  • Click Next
  • Specify the Output folder to be the location of the dzoneserver’s WebContent directory such as: C:\workspace\dzone-server\WebContent\
  • Click Finish

Your project will open in the MXML code editor and you’ll see a file titled main.mxml. Open the file and add the Flex® application code from Listing 8. This code accesses the MyServiceImpl class in Java and returns the results to Flex.


<?xml version=”1.0” encoding=”utf-8”?>
<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml”
   creationComplete=”srv.getMyEntities()”>
  <mx:AMFChannel id=”myamf”
uri=”/dzone-server/spring/messagebroker/amf”/>
  <mx:ChannelSet id=”channelSet” channels=”{[myamf]}”/>
 <mx:RemoteObject id=”srv”
  destination=”myService” channelSet=”{channelSet}”/>
 <mx:DataGrid dataProvider=”{srv.getMyEntities.lastResult}”/>
</mx:Application>

Listing 8: Final main.mxml source file for accessing the Spring service

The code in Listing 8 sets up the AMFChannel for accessing the Spring service. Note that the destination “flexMyService” is the same as the bean you defined in the application-config. xml Spring configuration file. Also, you might have noticed that none of the Flex code contains anything specific to Spring. The Flex code doesn’t have to change, as the client code has no knowledge of the fact that Spring is being used on the server.

To get the dzone-server to update the deployed web application you may need to right-click the dzone-server project and select Refresh.

With all steps of the tutorial completed, you can start the Tomcat server in Eclipse and access the application at the following URL: http://localhost:8080/dzone-server/main.html

Running Application

Figure 1: The running application

To allow the Flex application to be launched in Run or Debug mode from Eclipse:

  • Right-click the dzone-flex project
  • Select Properties, then Flex Build Path
  • For the Output Folder URL, type http://localhost:8080/dzone-server/
  • Click OK to update the project properties

Now you can right-click the main.mxml file and select Run As > Flex Application or Debug As > Flex Application.

The running application displays the data that was hard coded in the MyServiceImpl Java class, as seen in Figure 1. Now you have a complete sample application using Spring, BlazeDS, and Flex

User Authentication

One of the benefits of using Spring is that it provides support for many common enterprise requirements, including security. In this section, you’ll expand on the basic application by using Spring Security to protect the service channel with role-based authentication.

To add security to the application you will need to download the following dependencies:

Then add the following files to the WEB-INF/lib directory in the dzone-server project:

  • cglib-2.2.jar
  • aspectjrt.jar (located in the aspectj.jar file)
  • asm-3.1.jar
  • asm-commons-3.1.jar
  • spring-security-acl-2.0.4.jar
  • spring-security-core-2.0.4.jar
  • spring-security-core-tiger-2.0.4.jar

<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.4.xsd”>
<http auto-config=”true” session-fixation-protection=”none”/>
 <authentication-provider>
  <user-service>
   <user name=”jeremy” password=”atlanta”
  authorities=”ROLE_USER, ROLE_ADMIN” />
 <user name=”keith” password=”melbourne”
authorities=”ROLE_USER” />
</user-service>
</authentication-provider>
</beans:beans>

Listing 9: application-Context-security.xml Spring Security Configuration File

The first step is to create a very basic Spring Security configuration file. This example will use hard-coded credentials, however in a real application a database or LDAP server will likely be the source of the credentials. These methods of authentication can be easily configured with Spring Security. To learn more about Spring Security and how to add more advanced configurations, see the project home page at: http://static.springframework.org/spring-security/site/

To create a basic Spring Security Configuration File:

  • Right-click WebContent/WEB-INF and then choose New > File
  • For the file name, type applicationContext-security.xml
  • Click Finish
  • Copy the code from Listing 9 to the file

This configuration allows the user to authenticate through the Blaze DZ channel. Add the security configuration to the Spring configuration in the web.xml by updating the contextConfigLocation param-value as shown in Listing 10.


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

Listing 10: web.xml File with Security Configuration Added

At this point, you need to update the Spring configuration file to secure the getMyEntities method on myService. To do this update the application-config.xml file with the code in Listing 11.


<?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”
  xmlns:security=”http://www.springframework.org/schema/security”
  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
  http://www.springframework.org/schema/security
  http://www.springframework.org/schema/security/spring-security-
2.0.4.xsd
  “>
  <flex:message-broker>
   <flex:secured />
  </flex:message-broker>
  <bean id=”myService” class=”MyServiceImpl”>
   <flex:remote-service/>
   <security:intercept-methods>
   <security:protect method=”getMyEntities” access=”ROLE_USER” />
  </security:intercept-methods>
 </bean>
</beans>

Listing 11: Updated application-config.xml Spring configuration file

If you run the Flex® application at this point, the getMyEntities service call will fail because the user is not authenticated.

Now that the server is configured to protect the service, you will update the Flex application to require the user to authenticate before loading data from the getMyEntities service method. The updated code shown in Listing 12 presents users with a login form (See Figure 2) until they are successfully authenticated. Once the user is authenticated, the view state is updated showing the DataGrid bound to the service results, and the service method is called.

Update the main.mxml page with the code in Listing 12. You can then run the application and login with one of the hard-coded username and password combinations from the applicationContext-security.xml configuration file.


<?xml version=”1.0” encoding=”utf-8”?>
<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml”>
<mx:Script>
  import mx.rpc.events.ResultEvent;
  import mx.rpc.events.FaultEvent;
  import mx.rpc.AsyncToken;
  import mx.rpc.AsyncResponder;
private function login():void {
var token:AsyncToken = channelSet.login(username.text, password.
text);
token.addResponder(new AsyncResponder(loginResult, loginFault));
}
private function loginResult(event:ResultEvent,
token:AsyncToken):void {
   //get data
   srv.getMyEntities();
   //change state
   currentState = “userAuthenticated”;
 }
 private function loginFault(event:FaultEvent, token:AsyncToken):void
{
invalidLogin = true;
}
</mx:Script>
<mx:AMFChannel id=”myamf”
uri=”/dzone-server/spring/messagebroker/amf”/>
<mx:ChannelSet id=”channelSet” channels=”{[myamf]}”/>
<mx:RemoteObject id=”srv”
destination=”myService” channelSet=”{channelSet}”/>
<mx:Boolean id=”invalidLogin”>false
<!-- Login Form -->
<mx:Panel id=”loginPanel” title=”Login Form”>
<mx:Label text=”Invalid username or password”
includeInLayout=”{invalidLogin}” visible=”{invalidLogin}” />
  <mx:Form defaultButton=”{loginButton}”>
   <mx:FormItem width=”100%” label=”Username”>
    <mx:TextInput id=”username”/>
   </mx:FormItem>
  <mx:FormItem width=”100%” label=”Password”>
 <mx:TextInput id=”password” displayAsPassword=”true” />
  </mx:FormItem>
    </mx:Form>
     <mx:ControlBar>
    <mx:Button id=”loginButton” label=”Login” click=”login()”/>
   </mx:ControlBar>
  </mx:Panel>
<mx:states>
 <mx:State name=”userAuthenticated”>
   <mx:RemoveChild target=”{loginPanel}” />
    <mx:AddChild>
   <mx:DataGrid dataProvider=”{srv.getMyEntities.lastResult}” />
  </mx:AddChild>
</mx:State>
</mx:states>
</mx:Application>

Listing 12: Update Flex Application

The Flex code in Listing 12 is very basic. It presents the user with the loginPanel until loginResult() is invoked by a successful login. The username and password parameters come from a login form and are passed to the channelSet’s login() method. On a successful login, the loginResult() handler function is called, and the post-login logic is invoked. In this case, the currentState is updated to userAuthenticated, which removes the login form and adds the DataGrid bound to the service call’s results. In addition, the getMyEntities service method is called to load the data.

Login Form

Now, you have a basic Flex®, Spring, and BlazeDS application protected with authentication.

Conclusion

In this Refcard, you first created a Spring bean that was exposed to the Flex client through BlazeDS using Spring BlazeDS Integration. Next, you secured your service by adding Spring Security, and basic Flex authentication. As you can see, the new Spring BlazeDS Integration project makes integrating Flex and Spring easy and straightforward. The combination of the two technologies creates a powerful platform for building robust RIAs. You can learn more about integrating Flex and Spring on the Spring BlazeDS Integration project site: http://www.adobe.com/devnet/flex/flex_java.html

About The Author

Photo of author Jon Rose

Jon Rose

Jon Rose is the Flex Practice Director for Gorilla Logic, an enterprise software consulting company located in Boulder, Colorado. He is an editor and contributor to InfoQ.com, an enterprise software community. Visit his website at: www.ectropic.com

Gorilla Logic, Inc. provides enterprise Flex and Java consulting services tailored to businesses in all industries. www.gorillalogic.com

Photo of author James Ward

James Ward

James Ward is a Technical Evangelist for Flex at Adobe. He travels the globe speaking at conferences and teaching developers how to build better software with Flex. Visit his websit at: www.jamesward.com

First Steps in Flex, co-authored by James, will give you just enough information, and just the right information, to get you started learning Flex--enough so that you feel confident in taking you own steps once you finish the book. For more information visit: http://www.firststepsinflex.com

Recommended Book

First Steps in Flex

First Steps in Flex will take you through your first steps on your way to becoming a powerful user interface programmer.

We’ve gone to great lengths to show you the world of Flex without burying you in information you don’t need right now. At the same time, we give pointers to places where you can go to explore more.

First Steps in Flex is the ideal starting point for any programmer who wants to quickly become proficient in Flex 3.


Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


Your download should begin immediately.
If it doesn't, click here.

Daily Dose: JBoss Application Server 7 is here!

Today, JBoss released the 7th version of their free, open-source Java EE-based application server. As JBoss' Lead Technical Director Mark Little states,It's taken us a while to get here and we've taken some pretty drastic and innovative steps along the...

0 replies - 19895 views - 07/12/11 by Ross Jernigan in Daily Dose

Eclipse Tools for Spring

The SpringSource Tool Suite

By Gordon Dickens

13,783 Downloads · Refcard 147 of 151 (see them all)

Download
FREE PDF


The Essential SpringSource Tool Suite Cheat Sheet

This cheat sheet covers the SpringSource Tool Suite (STS), an Eclipse-based IDE that includes many useful Spring developer plugins out of the box. These tools include visual editors, project validators, and a Spring dashboard. The suite can be used for development in Spring Roo, Groovy, Grails, Gradle, Spring tcServer, and Spring Insight. This Refcard will walk you through installation, configuration, validation, Bean navigation, Spring Aspect Oriented Programming, and analysis. Whether youre new to Spring development or a veteran on the framework, you need to get your hands on this card.
HTML Preview
Eclipse Tools for Spring: The SpringSource Tool Suite

Eclipse Tools for Spring:The SpringSource Tool Suite

By Gordon Dickens, Chariot Solutions

ABOUT SPRINGSOURCE TOOL SUITE

SpringSource Tool Suite (STS) is an Eclipse-based IDE with pre-installed plugins that provides valuable features for Spring developers. In addition to support for the core Spring framework, STS also provides visual editors, project validators, and Spring Dashboard for other projects such as Spring Roo, Grails, Groovy, Gradle, tcServer, and Spring Insight.

The main plugin for STS is Spring IDE, which provides the fundamental Spring tooling features. STS comes preconfigured with many other plugins such as M2Eclipse for Maven, Web Tools Platform (WTP), Data Tools Platform (DTP), and AspectJ Development Tools (AJDT) and JUnit tooling.

Why use STS?

  • Content aware XML Spring Bean editing and refactoring
  • Content-aware Spring shortcuts for Java classes
  • Visualizers for graphical configuration editing
  • Validators for project configuration
  • Dashboard
  • Spring tcServer and Insight
Getting STS

STS is available from SpringSource: http://www.springsource.com/developer/sts

STS version numbers are different than the Eclipse versions. When choosing versions from the Spring site, go the current version of STS to see the supported Eclipse versions.

When installing STS from the native installer, it prompts you to install optional products such as Spring Roo, Apache Maven, and tcServer Developer edition. If these features are already installed and configured, uncheck these products.

Already have Eclipse?

If you already have Eclipse 3.6, download the STS plugin as follows:

  1. Before installing STS, ensure you have the current JDK installed.
  2. Download the bookmarks file from: http://dist.springsource.com/release/TOOLS/composite/e3.6/bookmarks.xml.
  3. In Eclipse, select Preferences -> Install/Update -> Available Update Sites.
  4. Click the “Import…” button, select the downloaded “bookmarks. xml”, and click “Open” to finish the import.

If you are using another version of Eclipse, find installation instructions here: http://www.springsource.com/products/eclipsedownloads.

Manage the plugin sites from Help > Install New Software… Clicking the “Available Sites” link shows the currently configured plugin sites.

The Dashboard

When you start STS, one of the first things you will see is the Spring Dashboard. At the bottom of this view are two tabs: Dashboard and Extensions. The Dashboard tab contains five sections:

  1. Create – Spring, Java, Grails & Groovy Projects
  2. Updates – Update information for STS
  3. Tutorials – Spring, Security, Web, Web Flow, WS
  4. Help & Docs – Forums, JIRA, STS New & Noteworthy
  5. Feeds - RSS announcements from Spring and Spring Blog posts

The Extensions tab contains two tabs:

  1. Extensions tab provides options for installing Roo, Groovy, Grails, and other useful extensions such as Google (GWT & GAE), CloudFoundry, DataNucleus, EGit, FindBugs, PMD, and more.
  2. The Find Updates tab checks for extension updates.

Hot Tip

To Manage the Dashboard: Preferences > Spring > Dashboard Add Spring blogs like: http://gordondickens.com/wordpress/feed/

PROJECT CONFIGURATION

To take advantage of Spring tooling features, add the Spring Project Nature to each project. Then you can view the project in Spring Project Explorer and define bean config files and config sets.

If you’re using Maven, you can configure this in your pom.xml file using the maven-eclipse-plugin:



<build>
...
  <plugin>
	<groupId>org.apache.maven.plugins</groupId>
	<artifactId>maven-eclipse-plugin</artifactId>
	<version>2.8</version>
	<configuration>
	  <downloadSources>true</downloadSources>
	  <downloadJavadocs>true</downloadJavadocs>
	  <wtpversion>1.5</wtpversion>
	  <additionalBuildcommands>
		<buildCommand>
		  <name>org.springframework.ide.eclipse.core.springbuilder</
name>
		</buildCommand>
	  </additionalBuildcommands>
	  
	  <additionalProjectnatures>
		<projectnature>
		  org.springframework.ide.eclipse.core.springnature
		</projectnature>
	  </additionalProjectnatures>
	</configuration>
  </plugin>
...
</build>



Once the Maven Eclipse plugin is installed, you can generate the Eclipse project files from the command prompt with:


mvn eclipse:eclipse

Hot Tip

A project configured with Spring Project Nature will have an “S” over the project, bean config files and directory icons containing bean config files.
Spring Perspective

The Spring Perspective is an Eclipse perspective displaying views such as Spring Explorer and other standard Eclipse views: Servers, Spring Explorer, Task List, Outline, Console, Markers, and Progress. This is a convenient layout that can be customized to your liking.

Spring Explorer View

This view provides the ability to see the Bean Config files within Spring projects. Here you can view the beans graph visualizer, create bean config files, define Bean Config sets, define new beans, validate beans, and openf MVC request mappings.

Bean Config files are XML files defining beans and bean relationships within a project. If you are using a project and don’t remember where the Bean Config files are located, open Spring Explorer. Within Spring Explorer, right-click a config file and choose from several options:

  • Open Dependency Graph - the visualizer for bean relationships. This is the same as the “Bean Graph” tab available in the bean editor.
  • New Bean Definition - provides a dialog for entering bean definitions.
  • RequestMapping - opens a view for MVC applications showing all the request mappings configured in this file. Validate - validates the bean configuration file based on the Spring Bean
  • Validate - will validate the bean configuration file based on the Spring Bean validation configuration settings in preferences.
  • Properties - opens project beans, validation, config set dialog. In this dialog we have the option to scan for more configuration files with the “Scan” Button.
Window 1
Project Explorer View

This view provides you with the ability to look at the project by its component types such as Spring Elements, Bean Config Files, Bean Config Sets, Web Service components, Java Resources, and more.

Window 2

Once you have added Spring Project Nature to your project, you can create or mark bean config files.

Creating a Spring config file – From Package Explorer, click the directory for the XML file and choose:

File > New > Spring Bean Configuration File

Locating Spring config files - from Spring Explorer view, right-click the project:

Properties > Spring > Beans Support “Scan” button the directory for the XML file and choose: File > New > Spring Bean Configuration File

Hot Tip

Bean config files will appear with the “S” over the directory and file.
Bean Config Sets

Bean config sets allow you to group bean config files together. Using Config Sets provides the ability to validate beans and bean relationships defined within multiple bean config files. Validation also provides suggestions via content assist when editing.

This feature is particularly useful when you have infrastructure beans such as dataSource defined within a test config file and the application’s entity, services, etc defined in a common bean config file that is the same for all deployment platforms. You do not have the ability to assign config sets to any components or tests. This is unnecessary as STS performs cross-file validation on all config sets.

If the bean config files within a config set do not define all referenced beans, mark a config set by checking the “Is incomplete” checkbox. If checked, the BeansConfigValidator doesn’t complain about missing bean references within this config set.

Spring MVC Request Mappings

Spring MVC is very powerful and easy to configure using annotations. The MVC Request Mappings view displays the request mappings for an MVC project. In Spring Explorer, right-click an MVC project, config file, or config set and select RequestMappings to see the URL details in a tabular view. If it is not an MVC application, this view is empty. The view provides the following details:

  • Resource URL
  • Resource Method: GET, POST, etc.
  • Handler Method
  • JavaDoc

Within the view, Double click on line to go to the code.

Windows 3

STARTING A PROJECT FROM SCRATCH

Spring Project

This option is extremely bare bones and only creates a basic Java project with src directory and Spring Project Nature added. No Spring dependency jars or other structures are configured. It is recommended to use the Spring Template Projects instead.

See the Spring Dashboard for quick links to create Spring, Groovy, Grails, and Spring Roo projects.

Spring Template Project

From the File > New menu, you can create a Spring project using the predefined templates from SpringSource. These templates provide a convenient starting point for different Spring projects.

The projects created from these templates are configured as Maven projects with the necessary project (JAR) dependencies.

Note: Many of the templates may require manual updating of project configuration. Updating configuration is often in two main areas: version dependencies in pom.xml and bean config file namespaces for the latest project versions.

BEAN CONFIGURATION

Bean Editing

The bean editor in STS provides features beyond a standard XML editor. In the java editor, you are already familiar with content assist. Spring adds content assist when typing in bean declarations. For example, in the bean config editor (and throughout Eclipse), you can use camel case when typing bean names. This provides the ability to enter the class name without having to know the full package or spelling of the bean.

For example:

If you want to configure JmsTemplate, type <bean class=“JT”/> and press CTRL-Space after the “T” to get a long list of beans matching J and T. Narrow by <bean class=“JmT”/> then press CTRL-Space after the “T” to get a shorter list where you can choose JmsTemplate. The complete package and classname is entered for you.

When configuring properties of a bean, content assist provides you with the available properties that you can set in the XML config.

<bean id=“jmsTemplate” class=“…JmsTemplate”> <property name=“”/> </bean>

By hitting CTRL-Space within the quotes of the property name, you are prompted with all of the properties available to set.

Spring also provides XML templates to quickly insert config within the xml files. For example, on a blank line in the bean config editor, type “bean” and press CTRL-Space.

Windows 4

Choose Bean - Inserts a Bean Tag and below shows the example of what will be inserted into the code:

<bean id=”id” class=”class”>

</bean>

Hot Tip

View, add or modify XML bean templates in Preferences > Spring > Beans Support > XML Templates
Windows 5
Bean Editor Tabs

A series of Tabs will display at the bottom of the editor based on the content of the XML namespaces used. Overview tabs for specific namespaces include JDBC, Spring Integration, Spring Batch and Web Flow.

Windows 6
  • Source – The XML editor
  • Namespaces - Choose namespaces to include/exclude in the configuration file, without the risk of typos.
  • Configure the namespace discovery in Preferences > Spring > Beans Support > Namespaces
  • Overview - General overview of the beans within a bean definition file. A tree hierarchy shows the beans, nested beans and bean properties.
  • Namespace specific tabs – provide bean information for namespaces we have selected. Such as: context, jee, tx, etc.

Beans Graph – Display’s graphical representation of beans (see Visualizers below)

Hot Tip

<Configure the namespace discovery by selecting Preferences > Spring > Beans Support > Namespaces.

VALIDATION

Spring project validation rules are available in Preferences > Spring > Project Validators section.

Spring Validator

There is only one option to verify Spring is in the classpath. This validator is disabled by default. There are three categories: Bean validation, STS validation, and Spring validation.

Bean Validation

There are 15 rules available, most enabled by default. These rules validate bean names, aliases, deprecation, @Required annotation, constructor injection, and Autowired annotation types (@Autowired, @Resource, @EJB).

Bean Rule Description
Required Property Validates @Required annotation
Annotation-based
Auto wiring
Validates @Autowired, @Resource and @EJB annotations
Bean Alias Validates alias names associated with bean
Bean Class Validates a bean class
Bean Constructor
Argument
Validates non-abstract bean’s constructor arguments
Bean Definition Holder Validates Root bean’s name and aliases
Bean Definition Validates a bean’s definition
Bean Deprecation Validates init, destroy and setters are not deprecated
Bean Factory Validates a factory beans and factory methods
Bean Init and Destroy
Method
Validates non-factory beans init and destroy method
Bean Method Override Validates bean method override
Bean Property Validates bean’s property accessor method is in bean class
Bean Reference Validates bean references depends-on attribute, a value holder or collection type
XML Parsing Problems Validates XML file is parseaable
XSD Tool Annotation Validates attributes based on schema
STS Validator

The eight STS validator options are project-wide validation rules.
These validators are disabled by default.

STS Rule Description
Driver Manager Data Source Validates the project does not use this class
Bean Inheritance Recommends bean inheritance for simplification
Import Elements at Top Recommends imports before other bean definitions
Parent Beans not Abstract Validates that parent beans are not abstract
Too Many Beans Validates too many beans in file – approx. 80 beans
Unnecessary Ref Check for ref elements and recommends ref attribute instead. <property … ref=””/> instead of <property …><ref bean=””/></property>
Dedicated Namespace Syntax Checks for cases where dedicated namespaces can be used

Once enabled, from Package Explorer view, R-Click on the project and select validate.

STS Validation errors will be displayed in the Markers and Problems views.

Once corrected actions are made, you may need to remove the validation markers. R-Click on project > Spring Tools > Remove Validation Markers and then validate again.

Bean Refactoring

The Bean Config editor provides the ability to refactor bean definitions. In the editor, right-click on a bean definition, select “Refactor…” and you will see three options:

  • Refactor Property Element – Nested ref and value tags.
  • Move Bean Element (class)… - Move class to another package.
  • Rename Bean Element (id, class, property name)…- Rename bean id, can search for literal string references and similarly named classes.

BEAN NAVIGATION & ANALYSIS

Within STS, you can quickly open a bean or view bean cross references or bean outline from the Eclipse Search and Navigate menu options.

Finding Spring Beans

From Search > Beans, you can conduct a wildcard search for beans by name, class, property name, beans referencing, and child beans.

Navigate > Open Spring Bean displays a search box where you can search for class names using camel-case.

Beans Quick Cross References

Within the bean config editor, select Navigate > Beans Quick Cross References to show the beans cross references for the current bean file. From here, you can jump to the bean declaration.

Note:

  • Beans Cross References view is for Spring
  • Cross References view is for AspectJ
Beans Quick Outline

Within the bean config editor, select Navigate > Beans Quick Outline to display an outline list of all bean declarations and property settings. You can search for a specific bean by ID and click a bean to see its definition.

Beans Cross References View

This view shows cross references based on the open file. By default, this view is empty until you click the “Link with Editor” in the title bar of the view (gold arrows).

Windows 7

SPRING ASPECT ORIENTED PROGRAMMING (AOP)

Spring AOP support in STS is extends the installed AspectJ Development Tools (AJDT) plug-in.

Spring Aspects Tooling

Spring AOP support in STS extends the installed AspectJ Development Tools (AJDT) plug-in.

Right-click on a project. Under Spring Tools, there is an option to enable Spring Aspects Tooling. This enables AJDT weaving features within a project.

With this setting, AJDT weaves itself into JDT with features:

  • TD-aware reconciling/eager parsing
  • TD-aware content assist
  • TD-aware type hierarchies
  • Search for aspect elements using standard Java search and Open Java type

Source: http://wiki.eclipse.org/JDT_weaving_features

AOP Event Trace

The AOP Event Trace view provides log-like detail during a project build. The view logs information about the Spring IDE’s internal AOP model creation.

To enable this feature:

  • Add spring-aspects.jar to the project.
  • Right-click project > Spring Tools > Enable Spring Aspects Tooling.
  • Select Preferences > AspectJ Compiler > Other > Check Verbose & Pointcut matching timers.
Windows 9
Spring Pointcut Matches

From the Search menu, we can use Spring AOP Pointcut expressions and test pointcuts such as:

execution(void set*(*))

bean(transactionManager)

Windows 8

VISUALIZERS

STS provides the ability to graphically view and edit Spring configuration. The five visualizers are beans, Spring Integration, Spring Batch, Web Flow, and Aspects.

Beans Graph

The Beans Graph provides a visual diagram of the Beans and Bean Relationships within a config file or config set.

The Beans Graph provides a visual diagram of the Beans and Bean Relationships within a config file or config set.

Within a Bean Config file, the tab “Beans Graph” displays beans within the file.

Windows 10

From Project Explorer, expand the project under Spring Elements, right-click the Config Set name, and choose “Open Dependency Graph”.

Windows 11

Set preferences for Beans Graph in Preferences > Spring > Beans Support

  • Display Inner Beans
  • Display Infrastructure Beans
  • Display Extended Content (Autowired beans)

This feature is enabled by default in Preferences > Spring> Beans Support > Editor > Enable embedded graph pages.

Integration Graph

When using Spring Integration, the “integration-graph” tab is available in the beans config editor. The graph displays the standard Hohpe/Woolf diagrams from the Enterprise Integration Patterns book.

When using Spring Integration, the “integration-graph” tab is available in the beans config editor. The graph displays the standard Hohpe/Woolf diagrams from the Enterprise Integration Patterns book.

This visualizer is editable using the tool pallet on the left. The tool pallet only shows tools based on the namespaces included in the XML file.

Windows 12
Batch Graph

When using Spring Batch, you see the batch-graph tab in the beans config editor. This visualizer is editable.

Windows 13
Web Flow Graph

Spring Web Flow provides you with the ability to design Stateful page flows. The bean config editor provides the ability to edit the flows in XML or visually from the flow-graph tab.

Windows 14
Aspect Visualization

To see visualize Spring AOP aspects, select Preferences > Visualizer under Visualizers and then check Spring AOP Provider. You can also do this from the Visualizer view by clicking the down arrow in the view’s title bar and choosing preferences.

In the view tools, select the “Hide Unaffected Bars” to show only the classes affected by aspects.

Note: You do not need to enable Spring aspects tooling for this feature to work.

Windows 15

About The Authors

Gordon Dickens

Gordon Dickens is an instructor/mentor/consultant for Chariot Solutions (chariotsolutions.com) with experience in the IT consulting for over 15 years. Gordon’s background includes presenting at conferences and user groups on Spring, Groovy & Grails, with experience developing Spring, Hibernate, Grails, Roo and OSGi applications. Gordon blogs at technophile.gordondickens.com and actively tweets open source tips at (twitter.com/gdickens). Gordon is a contributor to Spring Roo in Action manning.com/rimple and very active in the Spring Framework, Roo, Spring Integration and Spring Batch projects. He currently teaches Maven and Spring as a Certified Spring Instructor by SpringSource.

Recommended Book

Spring Roo in Action Book

Roo is a lightweight Java development tool that works within existing processes, to rapidly produce high-quality, 100% Java code. Roo enforces correct coding practices and patterns and instantly integrates not only with Spring, but also with virtually every mainstream Java technology.

Roo in Action is unique book that teaches how to code Java in Roo, with a particular focus on Spring-based applications. It starts by getting into the Roo mindset, along with a quick-and-dirty guide to setting up Roo effectively. Through hands-on examples, readers will learn how Roo creates well-formed application structures and supports best practices and tools.

Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


Your download should begin immediately.
If it doesn't, click here.

Daily Dose: Spring Jumps Into M2 of Version 3.1.0

 Spring, the open source application framework, reached its "second and final milestone", and version 3.1 is now available. The new features include:

0 replies - 13508 views - 06/10/11 by Ross Jernigan in Daily Dose

Daily Dose: Release of jQuery 1.6

Version 1.6 of the jQuery, a widely-distributed JavaScript library, is ready for download. One of the most prominent improvements to jQuery 1.6 is the rewrite of the Attribute model. Thanks to these changes, overall event handling is enhanced. Case mapping of...

2 replies - 20038 views - 05/03/11 by Katie Mckinsey in Daily Dose

Daily Dose: Couchbase Gets Comfortable With New Couchbase Server

The newly-minted Couchbase has released their first major product, the Couchbase Server.  At this time, the Couchbase Server doesn't have Membase's scalability.  Essentially, the Couchbase Server is a clean build of the Apache CouchDB.  Future releases of...

0 replies - 19385 views - 03/21/11 by Katie Mckinsey in Daily Dose

Daily Dose: OpenJDK6 Leader Joseph Darcy Resigns Release Managment Duties

The leader of OpenJDK6, Joseph Darcy is stepping down from his release management duties for the project this week.  Kelly O'Hair will take on his responsibilities in the coming weeks.  Release management repositories for OpenJDK6 have already been passed...

1 replies - 17057 views - 03/04/11 by Katie Mckinsey in Daily Dose

Daily Dose: Apple's "Magical" iPad 2 Revealed!

The much-anticipated release of the iPad 2 revealed a host of upgrades.  Apple's iPad 2 includes a lot of the big, expected new features like a dual-core 1GHz A5 processor and cameras on the front and back.  FaceTime video conferencing and VGA resolution...

0 replies - 17875 views - 03/03/11 by Katie Mckinsey in Daily Dose

Daily Dose: JSON Rendering Engine Marches to a New "Tempo"

Tempo is a new JSON rendering engine used for building data templates in pure HTML.  When you build the data templates, there is a clear separation between JavaScript and HTML files (no JS in your HTML). Fast rendering speeds are standard and the program...

0 replies - 18327 views - 03/01/11 by Katie Mckinsey in Daily Dose

Daily Dose: Seam 3 Release Candidate On the Way

The second beta for Seam 3 was released this week.  This final beta includes several enhanced features, such as consolidated API documentation and many bugfixes.  The candidate release (CR) is expected by the end of this month.  Final release could be...

0 replies - 24066 views - 02/15/11 by Katie Mckinsey in Daily Dose

Daily Dose: Spring 3.1 Milestone 1 is Loaded

The Spring Framework team has announced the first milestone release of Spring Framework 3.1. New features include enhanced Bean definition profiles,  comprehensive caching support, and unified property management.  Chris Beams of SpringSource is posting a...

1 replies - 23730 views - 02/13/11 by Katie Mckinsey in Daily Dose

Daily Dose - NoSQLs Join Forces

NoSQL backers Membase and CouchOne just announced that they are merging to create Couchbase, Inc.  Combining the caching and clustering technology of Membase, and the document database capabilities of CouchDB, the newly-minted Couchbase company will be...

0 replies - 18208 views - 02/09/11 by Katie Mckinsey in Daily Dose

Daily Dose - Spring Data Graph - Bringing NoSQL, MapReduce, and Cloud Data to Spring Apps

A new project from Spring has been announced recently with its first milestone release.  Spring Data Graph 1.0 will focus on making it simpler for developers to build Spring-based apps that hook into things like MapReduce, NoSQL data stores, and cloud data...

3 replies - 13440 views - 01/24/11 by Mitchell Pronsc... in Daily Dose

Daily Dose - Eclipse 3.7 and 4.1 Hit Milestone 4

Eclipse 3.7 "Indigo" and Eclipse 4.1, which is still aimed at early adopters, received new features in milestone 4 this week.  For both Eclipse versions, the milestone brings Equinox updates for the OSGi R4.3 spec, memory usage upgrades for p2, and...

0 replies - 22594 views - 12/14/10 by Mitchell Pronsc... in Daily Dose