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.

Fortunatelly 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.

Tags:  Java  JavaFX  Spring  DI 
Last blog articles:
Disable startup logs of Tomcat in Eclipse
Obchodování pro programátory
Mým fuckupům
Ubuntu: Login loop
Leaving LinkedIn

Tags:
Java Ubuntu česky Gradle personal úvaha Software-architecture Eclipse DIY children React DisplayLink AI Spring JavaScript AspectJ thoughts startup podnikání neuron Tomcat SSH LXC JavaFX Immutables Gnome3 GIT FatJar Edison technologies science procrastination pokusy linux lambda kvas ellipsis destilace chemie alkohol VisualVM Upstart Selenium REST PrimeFaces Log4j Jooq Jackson JSF Debug DI CSS

Last tweets: