Ivo
Ivo

Reputation: 450

Why the need of a specific Spring FXML Loader

I am looking at this example: Building Applications in JavaFX 2.0 and they show a custom SpringFxmlLoader:

import java.io.IOException;
import java.io.InputStream;
import javafx.fxml.FXMLLoader;
import org.springframework.context.ApplicationContext;
public class SpringFxmlLoader
{
private ApplicationContext context;

public SpringFxmlLoader(ApplicationContext context)
{
    this.context = context;
}

public Object load(String url, Class<?> controllerClass) throws IOException
{
    InputStream fxmlStream = null;
    try
    {
        fxmlStream = controllerClass.getResourceAsStream(url);
        Object instance = context.getBean(controllerClass);
        FXMLLoader loader = new FXMLLoader();
        loader.getNamespace().put("controller", instance);
        return loader.load(fxmlStream);
    }
    finally
    {
        if (fxmlStream != null)
        {
            fxmlStream.close();
        }
    }
}
}`

Why does one need to create a specific spring FXML Loader? I mean, even with a simple fxml loader, when you load a fxml like this:

AnchorPane page = (AnchorPane) FXMLLoader.load(TabePaneGraph.class.getResource("Sample.fxml")); the Sample Controller is called anyways and any initialization is still done. I am trying to understand the motivation behind this specific custom SpringFxmlLoader implementation.

Upvotes: 2

Views: 2381

Answers (2)

Andy Till
Andy Till

Reputation: 3511

There are multiple ways to skin a cat. I'm guessing the motivation to use spring in that article is because many web developers would be familiar with it. It also might make it look more like an alternative to a Java EE application. Which it is, but not because you can use spring with it.

You don't need any dependency injection framework to develop with JavaFX, in fact we need to look carefully at our dependencies because they will add to download time if you are expecting users to download your application.

Upvotes: 1

Puce
Puce

Reputation: 38132

There are (at least) 2 ways, how to specify a controller:

  • declare the controller class in the FXML file: note that you specify the class not the instance here. The FXMLoader will create a new instance.
  • pass an existing instance (e.g. "this" or as here a bean instantiated with Spring) as the controller to the FXMLLoader
loader.getNamespace().put("controller", instance);

I'm not sure about this part, but I think it can be replaced with setController() in the latest JavaFX version.

Upvotes: 1

Related Questions