Tag Archives: Dependency injection

JavaFX: Instantiate Application within Spring Context

JavaFX application is typically instantiated via calling static method launch(…) on object inherited from Application:

import javafx.application.Application;

public class TestApp extends Application {
	public static void main(String[] args) {
		launch(args);
	}
}

But this hardly fits into IoC solution – in this case Spring Context. I was trying to find suitable solutions but failed. There is no simple way how to instantiate Application in dynamic way.

But there is workaround: Start application in static way, in start(…) method save created Application instance into static variable and then create Spring context. Instance of Application is accessible through static method.

So something like:

import org.apache.commons.lang3.Validate;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class TestApp extends Application {
	private static volatile TestApp singleton;
	
	public static void main(String[] args) {
		launch(args);
	}

	public static TestApp getSingleton() {
		Validate.notNull(singleton, "Not yet created instance of %s!", TestApp.class.getName());
		return singleton;
	}

	@Override
	public void start(Stage primaryStage) throws Exception {
		Validate.validState(singleton==null, "Only one instance of %s may be created!", getClass().getName());
		
		singleton = this;
		
		try (ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("/beans.xml")) {
			// Context initialized!!!
		}
	}
}

With following in beans.xml:

<bean id="app" class="test.TestApp" factory-method="getSingleton"/>

Then “app” behaves as plain bean and you can use it as such.