Google Guice module that loads two kinds of views

The code of my Guice Module looks like this:

public class FXMLModule extends AbstractModule {

    private final Locale locale = Locale.getDefault();
    private final ResourceBundle messages = ResourceBundle.getBundle("i18n.messages", locale);

    @Override
    protected void configure() {
        bind(Controller.class).annotatedWith(MainView.class).to(MainController.class);
        bind(Controller.class).annotatedWith(MovieView.class).to(MovieViewController.class);
    }

    @Provides @MainView
    public FXMLLoader mainViewLoader(@MainView Controller controller) {
        FXMLLoader loader = new FXMLLoader(locate("/jfx/fxml/MainView.fxml"), messages);
        loader.setController(controller);
        return loader;
    }

    @Provides @MovieView
    public FXMLLoader movieViewLoader(@MovieView Controller controller) {
        FXMLLoader loader = new FXMLLoader(locate("/jfx/fxml/MovieView.fxml"), messages);
        loader.setController(controller);
        return loader;
    }

    private URL locate(String location) {
        return getClass().getResource(location);
    }

}

Basically I want to inject fully configured FXMLLoaders into some Controller classes, so that they can work with the root nodes returned from the loaders without having to know anything about other controllers. The MainViewLoader gets injected into the Application class, and the MovieViewLoader gets injected into MainViewController. It works, but I’d have to write a provide method (with almost the same code) for every loader/controller. Any ideas how to make this more generic?

Leave a Reply

Your email address will not be published. Required fields are marked *