Maven + OSGi + Spring + JavaFX (+Ant)

We had to go through a number of steps to support the combination of Maven + OSGi + Spring + JavaFX-1.1 in our Swing-based application. This document describes all the steps and technology we’ve gone through to get it working.

! With JavaFX 1.2, some of the steps have changed. I will post a new entry covering the differences shortly.

Build / Compile

We use Maven as our build system, so JavaFX compilation must coexist with these.

Upload Dependencies to a Maven repository

First, we took every single Jar file in the JavaFX SDK 1.1 and uploaded them into Nexus, our development Maven repository. We took all jars from lib/shared and lib/desktop, uploaded them with groupID of javafx, artifactID matching the Jar name, version 1.1.

Building alongside Java code

To combat an explosion of modules, we determined that we wanted to have a src/main/fx source folder that is compiled and used right alongside src/main/java and src/main/resources. Furthermore, the JavaFX code needs to be able to refer to classes and interfaces in the same module as well as in any maven dependencies.

Our first attempt was to use the seemingly perfect fit, the m2-javafxc maven plugin. Early attempts seemed workable, but things started to fall apart and we had to abandon. Here are some of the issues:

  1. m2-javafxc is based on the maven-plexus-compiler. This compiler will only run once per module. So we were unable to have src/main/java and src/main/fx side-by-side
  2. m2-javafxc filters out anything other than .fx files. So we couldn’t have java and fx intermingled inside a single source folder.
  3. Unfortunately, m2-javafxc is supported by only one individual, and barely used by the community. While the codebase is not large or complicated, this does represent a bit of a risk.

Next, we we noticed that the SDK includes an ant task, something easily runnable in maven. So, we built up a working ant script. If you look carefully, you will notice it takes three parameters. These are covered below.

<project name="compile-jfx" basedir="." xmlns:artifact="urn:maven-artifact-ant">
	<target name="compile.jfx" depends="check-if-should-build" if="should-build">
		<path id="javafxc.class.path">
			<fileset dir="${localRepo}">
				<include name="javafx/**/${javafx.version}/*-${javafx.version}.jar" />
			<pathelement path="${compile.classpath}" />
		<echo message="localRepo: ${localRepo}" />
		<echo message="jfx ver: ${javafx.version}" />
		<property name="compiler.class.path" refid="javafxc.class.path" />
		<echo message="jfxc classpath: ${compiler.class.path}" />
		<!-- create output directories: -->
		<mkdir dir="target/fxclasses" />
		<mkdir dir="target/classes" />
		<mkdir dir="target/clover/classes" />
		<taskdef resource="" classpathref="javafxc.class.path" />
		<javafxc srcdir="src/main/fx" destdir="target/fxclasses" includes="**/*.fx" compilerclasspath="${compiler.class.path}" />
		<!-- copy output files to two places to deal with clovery issues: -->
		<fileset dir="target/fxclasses" id="fxclasses" />
		<copy todir="target/classes">
			<fileset refid="fxclasses" />
		<copy todir="target/clover/classes">
			<fileset refid="fxclasses" />
	<target name="check-if-should-build">
		<available file="src/main/fx" property="should-build" />
		<echo message="should-build: ${should-build}" />

To integrate into maven, we use the following snippet. It ties into the standard lifecycle, as you see, and happens just after src/main/java is compiled. It supplies three parameters to the ant script:

  • compile.classpath — the modules’s dependecy classpath
  • localRepo — the root of the local repository
  • javafx.vesion — the version of JavaFX to build with.

The last two parameters are used in the script to build the classpath to insure all the JavaFX libraries are present during compilation.

                            <property name="compile.classpath" refid="maven.compile.classpath"/>
                            <property name="localRepo" value="${settings.localRepository}"/>
                            <property name="javafx.version" value="${javafx.version}"/>
                            <ant antfile="">
                                <target name="compile.jfx" />
                    <!-- needed to compile javafx -->

Working Around Bugs

Ant Mojo

Next, we tried to wrap the above into a Maven plugin via the nifty Ant script-driven Mojo concept. However, I could not specify dependencies as I could with a Java mojo, and I was unable to get maven to pass the compile classpath into the script


It turns out, if you have a multimodule project (we do) and you have multiple invocations of maven-antrun-plugin, the classpath gets set once, by the first run. We had the choice of putting every dependency on every antrun, or the light hack of having an empty antrun in the parent project with every dependency specified.


When doing a build that includes Clover numbers, clover changes the build classpath to include the artifact with the clover classifier instead of the regular one. We were putting our result classes directly into target/classes

javafxc crash

A dependency on org.apache.felix:org.osgi.compendium will cause the javafxc ant task to crash, hard, with a JVM dump. I suspect it is the javax-servlet 1.0.0, but I’m too lazy to prove that.

+- org.apache.felix:org.osgi.compendium:jar:1.2.0:compile
|  +- org.apache.felix:javax.servlet:jar:1.0.0:compile
|  \-

OSGi / Runtime

The above gets us to a compiling and building state. However, our target platform is OSGi, specifically the Felix implementation. We need to be able to supply the JavaFX runtime classes to other bundles.

The javafx-runtime bundle

Rather than packaging each SDK jar individually into a bundle, we just dropped all of them into a single mega bundle. The following POM accomplishes this:

 <project xmlns="" xmlns:xsi="" xsi:schemaLocation="">
    <!-- the <packaging> pulls bundle from the parent's properties -->
        This bundle simply wraps the various javafx-compiled jars as a bundle.
                        <!-- embed all compile and runtime scope dependencies -->
                        <!-- <Embed-Dependency>*;scope=compile;artifactId=!log4j|javafxc</Embed-Dependency> -->

You can alternately use Eclipse to export a bundle like this, see the post Running a JavaFX script from an OSGi bundle– generally a good article, but slightly skewed from our purpose.

The bundle created above is not quite perfect; some imports marked optional are probably not optional, but are for parts we aren’t using just yet, like sound, or applets. It is missing all the native code shipped with the SDK, which probably has a performance impact. We also haven’t tested a fully-featured screen yet. Finally, there is another problem, which we’ll see in the next section.

Integrating JavaFX into a Swing Application

I can’t create a Scene!

There is a pretty nice article called How to Use JavaFX in Your Swing Application on the main JavaFX blog. It gives details for how to convert a Scene subclass into a JComponent for use in a swing app. The only problem with that: With the javafx-runtime bundle above, I always get a NullPointerException during some StyleSheet intialization. Even when we do it from the command-line, the result is the same. Again, the javafx-runtime bundle is not quite perfect, and I think that this bears that out.

Getting the JComponent

So, we had a workaround: Extend CustomNode, then create a Scene in Java and inject the custom node in. The class below has a field called node, which is of type javafx.scene.Node, set in by Spring (see next section). We steal some of the code from the above link to help with the final extraction. Also note, we had to duplicate in our package, since it is package-protected in the SDK.

        Scene scene = new Scene(true);
        Sequence&lt;Node&gt; seq = new SingletonSequence&lt;Node&gt;(TypeInfo.getTypeInfo(Node.class), node);
        // stolen from by Richard Bair and Jasper Potts:
        String helperName = "com.sun.javafx.scene.JSGPanelSceneImpl";
        FXClassType type = FXContext.getInstance().findClass(helperName);
        FXObjectValue panelSceneImpl = type.allocate();
        panelSceneImpl.initVar("scene", FXLocal.getContext().mirrorOf(scene));
        FXValue jsgPanelV = type.getVariable("jsgPanel").getValue(panelSceneImpl);
        JComponent jsgPanel = (JComponent) ((FXLocal.ObjectValue) jsgPanelV).asObject()

Working with Spring

The last piece of the puzzle is the ability to allow Spring to create JavaFX instances and set properties on them. Here is an example JavaFX class:

package whatever;
import javafx.scene.*;
import javafx.scene.paint.*;
import javafx.scene.shape.*;
import javafx.scene.text.*;
public class EDText extends CustomNode {
    var text:String = Dialog.MESSAGE;
    override public function create():Node {
        return Group {
            content: [
                Rectangle {
                    width: 300
                    height: 200
                    fill: Color.BLUE
                Text {
                    x: 20
                    y: 20
                    content: bind text
                    fill: Color.WHITE
        }; // endgroup
    function setDisplayString(newValue:String) {
        text = newValue;

It has a single operation, setDisplayString(). Then came this Spring config snippet to access it:

    <bean id="edNode" class="org.bjc.pt2.authentication.ui.EDText">
        <property name="displayString" value="set a value from spring!"/>

… which of course doesn’t work. JavaFX infers that the setter has a return value because none was specified. Spring is looking for public void setDisplayString(String) but finds public string setDisplayString(String) and complains. Minor tweak to the JavaFX code for the function declaration:

 function setDisplayString(newValue:String):Void {

And it’s all happy!

This entry was posted in java and tagged , , , , , . Bookmark the permalink.

2 Responses to Maven + OSGi + Spring + JavaFX (+Ant)

  1. The_Wizard_of_wind_Oz says:

    Very good step by step tutorial.

    For those interested, I have found out how to easily configure Maven to compile JavaFX classes alongside with Java classes:

    The only drawback is that Java classes must be separated from the JavaFX classes (which means two separate projects).

  2. pforhan says:

    Thanks for the link. The site discusses the same problem (only one plexus compiler per module) that I mention in “Building alongside Java code”. We have an OSGi project with lots of small bundles/modules — the thought of doubling all those was scary, so we implemented the solution above.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>