java - 每个上下文一个实例的依赖注入(inject)

标签 java javafx javafx-2 javafx-8

我正在开发一个应用程序,其中有一个包含 3 个项目的菜单:A、B、C

每个项目都会导致多个屏幕的流程。例如。如果单击 A,则我们得到 A1 -> A2 -> A3。

这对于 B 和 C 来说是相同的。

对于每个Ai View (FXML),还有一个相应的 Controller 。 屏幕是动态创建的。 IE。除非 A1 完成,否则不会创建 A2。

请注意,Ai 和 Bi Controller 是同一类的实例。

我希望将一个单实例模型注入(inject)到所有 Controller 实例(每个流创建的所有 Controller 实例)。例如。将创建一个实例并为 A1、A2、A3 Controller 实例提供服务。

有没有办法使用 Google Guice 来实现此目的,或者使用其他框架来实现此目的?

谢谢!

最佳答案

您可以使用 Controller 工厂将依赖项注入(inject)到 Controller 中。简而言之,如果您有某种模型类,则可以使用 Controller 工厂将值传递给 Controller ​​的构造函数:

Model model = ... ;

Callback<Class<?>, Object> controllerFactory = type -> {

    try {

        for (Constructor<?> c : type.getConstructors()) {
            if (c.getParameterCount() == 1 && c.getParameterTypes()[0] == BookingModel.class) {
                return c.newInstance(model);
            }
        }

        // no appropriate constructor: just use default:
        return type.newInstance(); 

    } catch (Exception exc) {
        throw new RuntimeException(exc);
    }

};

FXMLLoader loader = new FXMLLoader(getClass().getResource("/path/to/fxml"));
loader.setControllerFactory(controllerFactory);
Parent view = loader.load(); 

因此,在您描述的情况下,您将为“A”流创建一个模型,从该模型创建 Controller 工厂,然后在加载 A1、A2 和 A3 时使用该 Controller 工厂。然后创建另一个模型实例,即第二个模型实例的 Controller 工厂,并使用该 Controller 工厂加载 B1、B2 和 B3。

为了更具体地说明这一点,考虑一个酒店房间预订应用程序,我们可以将其分为三个部分(出于演示目的):设置抵达日期、设置出发日期和确认预订。这三个部分都需要访问相同的数据,这些数据将保存在模型类中。我们还可以使用该模型类来维护流程的当前状态;例如我们处于三个预订步骤(到达、离开、确认)中的哪一个。例如:

public class BookingModel {

    private final ObjectProperty<LocalDate> arrival = new SimpleObjectProperty<>();
    private final ObjectProperty<LocalDate> departure = new SimpleObjectProperty<>();
    private final BooleanProperty confirmed = new SimpleBooleanProperty();
    private final ObjectProperty<Screen> screen = new SimpleObjectProperty<>();

    public enum Screen {
        ARRIVAL, DEPARTURE, CONFIRMATION
    }

    public BookingModel() {
        arrival.addListener((obs, oldArrival, newArrival) -> {
            if (departure.get() == null || departure.get().equals(arrival.get()) || departure.get().isBefore(arrival.get())) {
                departure.set(arrival.get().plusDays(1));
            }
        });
    }

   // set/get/property methods for each property...

}

每个步骤都有一个 FXML 和一个 Controller ,每个 Controller 都需要访问同一流程中的步骤共享的模型实例。所以我们可以这样做:

public class ArrivalController {

    private final BookingModel model ;

    @FXML
    private DatePicker arrivalPicker ;

    @FXML
    private Button nextButton ;

    public ArrivalController(BookingModel model) {
        this.model = model ;
    }

    public void initialize() {

        arrivalPicker.valueProperty().bindBidirectional(model.arrivalProperty());

        arrivalPicker.disableProperty().bind(model.confirmedProperty());

        nextButton.disableProperty().bind(model.arrivalProperty().isNull());
    }

    @FXML
    private void goToDeparture() {
        model.setScreen(BookingModel.Screen.DEPARTURE);
    }
}

public class DepartureController {
    private final BookingModel model ;

    @FXML
    private DatePicker departurePicker ;

    @FXML
    private Label arrivalLabel ;

    @FXML
    private Button nextButton ;

    public DepartureController(BookingModel model) {
        this.model = model ;
    }

    public void initialize() {
        model.setDeparture(null);

        departurePicker.setDayCellFactory(/* cell only enabled if date is after arrival ... */);

        departurePicker.valueProperty().bindBidirectional(model.departureProperty());

        departurePicker.disableProperty().bind(model.confirmedProperty());

        arrivalLabel.textProperty().bind(model.arrivalProperty().asString("Arrival date: %s"));

        nextButton.disableProperty().bind(model.departureProperty().isNull());

    }


    @FXML
    private void goToArrival() {
        model.setScreen(BookingModel.Screen.ARRIVAL);
    }

    @FXML
    private void goToConfirmation() {
        model.setScreen(BookingModel.Screen.CONFIRMATION);
    }
}

public class ConfirmationController {

    private final BookingModel model ;

    @FXML
    private Button confirmButton ;
    @FXML
    private Label arrivalLabel ;
    @FXML
    private Label departureLabel ;

    public ConfirmationController(BookingModel model) {
        this.model = model ;
    }

    public void initialize() {

        confirmButton.textProperty().bind(Bindings
                .when(model.confirmedProperty())
                .then("Cancel")
                .otherwise("Confirm"));

        arrivalLabel.textProperty().bind(model.arrivalProperty().asString("Arrival: %s"));
        departureLabel.textProperty().bind(model.departureProperty().asString("Departure: %s"));
    }

    @FXML
    private void confirmOrCancel() {
        model.setConfirmed(! model.isConfirmed());
    }

    @FXML
    private void goToDeparture() {
        model.setScreen(Screen.DEPARTURE);
    }
}

现在我们可以创建一个“预订流程”

private Parent createBookingFlow() {
    BookingModel model = new BookingModel() ;
    model.setScreen(Screen.ARRIVAL);
    ControllerFactory controllerFactory = new ControllerFactory(model);
    BorderPane flow = new BorderPane();

    Node arrivalScreen = load("arrival/Arrival.fxml", controllerFactory);
    Node departureScreen = load("departure/Departure.fxml", controllerFactory);
    Node confirmationScreen = load("confirmation/Confirmation.fxml", controllerFactory);

    flow.centerProperty().bind(Bindings.createObjectBinding(() -> {
        switch (model.getScreen()) {
            case ARRIVAL: return arrivalScreen ;
            case DEPARTURE: return departureScreen ;
            case CONFIRMATION: return confirmationScreen ;
            default: return null ;
        }
    }, model.screenProperty()));

    return flow ;
}

private Node load(String resource, ControllerFactory controllerFactory) {
    try {
        FXMLLoader loader = new FXMLLoader(getClass().getClassLoader().getResource(resource));
        loader.setControllerFactory(controllerFactory);
        return loader.load() ;
    } catch (IOException exc) {
        throw new UncheckedIOException(exc);
    }
}

按照答案开头的模式定义 ControllerFactory:

public class ControllerFactory implements Callback<Class<?>, Object> {

    private final BookingModel model ;

    public ControllerFactory(BookingModel model) {
        this.model = model ;
    }

    @Override
    public Object call(Class<?> type) {
        try {

            for (Constructor<?> c : type.getConstructors()) {
                if (c.getParameterCount() == 1 && c.getParameterTypes()[0] == BookingModel.class) {
                    return c.newInstance(model);
                }
            }

            // no appropriate constructor: just use default:
            return type.newInstance(); 

        } catch (Exception exc) {
            throw new RuntimeException(exc);
        }
    }

}

如果我们需要多个“流”,这将起作用:

public class BookingApplication extends Application {

    @Override
    public void start(Stage primaryStage) {

        SplitPane split = new SplitPane();
        split.getItems().addAll(createBookingFlow(), createBookingFlow());
        split.setOrientation(Orientation.VERTICAL);

        Scene scene = new Scene(split, 600, 600);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private Parent createBookingFlow() {
        // see above...
    }

    private Node load(String resource, ControllerFactory controllerFactory) {
        // see above...
    }

    public static void main(String[] args) {
        launch(args);
    }
}

完整示例 as a gist .

我不清楚如何使用依赖注入(inject)框架(例如 Spring)轻松设置它。问题是控制预订模型创建的粒度:您不希望它具有单例范围(因为不同的流程需要不同的模型),但您也不希望原型(prototype)范围(因为同一个 Controller 中的不同 Controller )流量需要相同的模型)。从某种意义上说,您需要类似于“ session ”范围的东西,尽管这里的 session 不是 HttpSession 而是与“流”相关的自定义 session 。据我所知,Spring 中没有办法概括 session 的定义;尽管其他具有更多 Spring 专业知识的人可能有办法,并且其他 DI 框架的用户可能知道这在这些框架中是否可行。

关于java - 每个上下文一个实例的依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41708755/

相关文章:

java - 从 java 进程获取输出

templates - JavaFX 2.0-样式/模板现有控件

java - 使用 JDom2 解析 HTML 时引号导致 IllegalNameException

java - 如何停止另一个类(class)的连续声音循环?

java - 如何仅显示 JComponent/SwingNode/Java FX Pane 的一部分

java - 格里芬-JavaFX : View throws NPE concerning the model

java - 显示图像时内存消耗增加 50 MB

java、lucene、searcher索引器问题怎么办呢?

java - 如何在 hbm.xml 文件中的 hibernate 中创建复合主键

java - 在 OS X 上启动终端并使用 Java 运行命令