I wanted to make JavaFX programming easier with the Spring Framework

Overview

Actually, it's the Nth decoction, but ... I mean, it may not be the best practice because I had tried and errored when there was no this article. not.

point

Description in the class to be ComponentScan

MainApp.java


/**
 *Startup class
 * @author ysrken
 */
@ComponentScan
public class MainApp extends Application {
    private static ConfigurableApplicationContext context;
    
    /**
     *main function
     * @param args command line arguments
     * @throws Exception Run-time exception
     */
    public static void main(String[] args) throws Exception {
        //Since this context will be reused in the future, I dared to make it a static variable as described above.
    	context = new AnnotationConfigApplicationContext(MainApp.class);
        launch(args);
    }

    /**
     *JavaFX startup process
     * @param stage Stage information
     * @throws Exception Run-time exception
     */
    public void start(Stage stage) throws Exception {
        //It is generated safely, but the point is that it is getBean
        FXMLLoader loader = new FXMLLoader();
        loader.setControllerFactory(MainApp.getApplicationContext()::getBean);
        Parent rootNode = (Parent) loader.load(getClass().getResourceAsStream("/fxml/MainView.fxml"));
        Scene scene = new Scene(rootNode);
        stage.setScene(scene);

        mainStage.show();
    }
    
    /**
     *Used to route the ApplicationContext
     * @return Shared ApplicationContext
     */
    public static ApplicationContext getApplicationContext() {
    	return context;
    }
    
    /**
     *JavaFX termination process
     * @throws Exception Run-time exception
     */
    @Override
    public void stop() throws Exception {
        context.close();
    }
}

The important part here is " ConfigurableApplicationContext context ", which is used bygetApplicationContext ()when creating other windows. In other words, when using FXMLLoader, set the context asloader.setControllerFactory (MainApp.getApplicationContext () :: getBean);instead of just doingnew FXMLLoader (). This will extend the Spring Framework DI to the window's Controller and Model.

Description in Controller

Controller.java


@Component
//@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class Controller{
    /**
     * Model
     */
    @Autowired
    Model model;

    /**
     *Initialization
     */
    public void initialize() {
        ~~~
    }
}

By setting the context as described above, the Model will be loaded just by @Autowired. If you plan to create multiple Controllers and Models, uncomment the SCOPE_PROTOTYPE specification.

Description in Model

Model.java


@Component
//@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class Model{
    /**
     *Initialization
     */
    publicModel() {
        ~~~
    }
}

I'm glad that @Autowired works even in Model.

Other description

I think that the class you want to DI has @Component etc., but when you create an instance of a class that uses @ Autowired inside other than the above Controller relation, write as follows. Let's go.

sample.java


@Component
public class SampleClass {
    /**
     * Model
     */
    @Autowired
    Hoge hoge;

    ~~~~~~
}

// OK
final SampleClass x = MainApp.getApplicationContext().getBean(SampleClass.class);
// NG
final SampleClass y = new SampleClass();

Reference material

-Create your own FXMLLoader to inject SpringBean

Recommended Posts

I wanted to make JavaFX programming easier with the Spring Framework
I tried to link JavaFX and Spring Framework.
I wanted to gradle spring boot with multi-project
The story I wanted to unzip
I just wanted to logrotate with log4j 2
I wanted to add @VisibleForTesting to the method
Follow from the root node to the lower node with JavaFX ~ I know the directions ~
I used Docker to solidify the template to be developed with spring boot.
After all I wanted to preview the contents of mysql with Docker ...
I tried to make Basic authentication with Java
I wanted to make (a == 1 && a == 2 && a == 3) true in Java
I tried to make a simple game with Javafx ① "Let's find happiness game" (unfinished)
I wanted to start the AP server and debug with just the Maven command
I tried what I wanted to try with Stream softly.
I tried to make a simple game with Javafx ① "Let's find happiness game" (unfinished version ②)
I tried to implement file upload with Spring MVC
I tried to organize the cases used in programming
05. I tried to stub the source of Spring Boot
I tried to reduce the capacity of Spring Boot
I tried to get started with Spring Data JPA
I want to dark mode with the SWT app
I created an api domain with Spring Framework. Part 1
I wanted to develop PHP with vscode remote container
I made a function to register images with API in Spring Framework. Part 1 (API edition)
I used to make nc (netcat) with JAVA normally
I made a function to register images with API in Spring Framework. Part 2 (Client Edition)
I tried to make an introduction to PHP + MySQL with Docker
I tried to increase the processing speed with spiritual engineering
Make Docker confusing with Pokemon and make it easier to attach
I want to make a list with kotlin and java!
I just wanted to make a Reactive Property in Java
I want to make a function with kotlin and java!
I have summarized the articles that programming beginners referred to.
What I was addicted to with the Redmine REST API
I want to distinct the duplicated data with has_many through
I tried to get started with Swagger using Spring Boot
I tried upgrading from CentOS 6.5 to CentOS 7 with the upgrade tool
I want to pass the startup command to postgres with docker-compose.
I summarized the collection framework.
[Spring Boot] I want to add my own property file and get the value with env.getProperty ().
I tried to solve the problem of "multi-stage selection" with Ruby
I want to make a button with a line break with link_to [Note]
I want to understand the flow of Spring processing request parameters
I want to return to the previous screen with kotlin and java!
I tried connecting to MySQL using JDBC Template with Spring MVC
I tried to implement the image preview function with Rails / jQuery
What I did in the migration from Spring Boot 1.4 series to 2.0 series
I tried to make an Android application with MVC now (Java)
I tried to check the operation of gRPC server with grpcurl
What I did in the migration from Spring Boot 1.5 series to 2.0 series
[Java] I tried to make a maze by the digging method ♪
[Java] I want to perform distinct with the key in the object
I want to control the default error message of Spring Boot
I tried to make a group function (bulletin board) with Rails
A story that I wanted to write a process equivalent to a while statement with the Stream API of Java8
I tried to figure out the flow when performing image analysis with Vision Framework and Core ML
I went to JJUG CCC 2019 Spring
Make a slideshow tool with JavaFX
Programming with ruby (on the way)
I tried to interact with Java
I tried to explain the method