Search code examples
spring-bootjavafxsubclassextendsimplements

Spring Boot - Impossible for JavaFX app to implement SmartLifeCycle?


I am building a JavaFX app and i want it to implement Spring's SmartLifeCycle interface to perform tasks when the main class terminates. A JavaFX main class must extend the Application class which contains a stop() method. The SmartLifeCycle interface also contains a stop method. It looks like these 2 methods refuse to co-exist even if they have different method signatures. The JavaFX method extended from the Application class has no parameters and throws an exception while the implemented method from SmartLifeCycle takes a Runnable object as an argument.

Is it possible for both these methods to exist in the same class? Both are required to implement by subclasses therefore the compiler complains no matter what i do.

Thanks


Solution

  • The Application abstract class has the following method:

    public void stop() throws Exception {}
    

    And the SmartLifecycle interface has the following method, inherited from Lifecycle:

    void stop();
    

    As you can see, one can throw an Exception and the other cannot. If you want to extend Application and implement SmartLifecycle, then you can't have throws Exception in your overridden stop() method.

    public class MySpringJavaFxApp extends Application implements SmartLifecycle {
    
        @Override
        public void start(Stage primaryStage) throws Exception {
            // ...
        }
    
        @Override
        public void stop() {
            // ...
        }
    
        // other methods that need to be implemented...
    }
    

    But note you have to override stop() to remove the throws clause. Otherwise the methods clash (Application#stop is not abstract, thus tries to implement Lifecycle#stop in this situation).