每个上下文一个实例的依赖注入

Dependency Injection of One Instance Per Context

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

每个项目都会导致多个屏幕的流动。例如。如果 A 被点击,那么我们得到 A1 -> A2 -> A3.

B 和 C 也一样

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

请注意 Ai 和 Bi 控制器是同一个 class 的实例。

我想将一个一个实例模型注入所有控制器实例(每个流创建的所有控制器实例)。例如。将创建一个实例并为 A1、A2、A3 控制器实例提供服务。

有没有办法使用 Google Guice 或其他框架来达到这种目的?

谢谢!

您可以使用控制器工厂将依赖项注入到控制器中。所以简而言之,如果你有某种模型 class,你可以使用控制器工厂将值传递给控制器​​的构造函数:

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" 流程创建一个模型,从该模型创建控制器工厂,然后在加载 A1、A2 和 A3 时使用该控制器工厂。然后创建另一个模型实例,即第二个模型实例的控制器工厂,并使用该控制器工厂加载 B1、B2 和 B3。

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

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 和一个控制器,每个控制器都需要访问同一流程中步骤共享的模型实例。所以我们可以这样做:

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);
    }
}

现在我们可以用

创建一个"booking flow"
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);
        }
    }

}

如果我们需要多个 "flows":

,这将起作用
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

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

你调查过 Guice custom scopes 了吗?

内置的(Session 和 Singleton)似乎不能满足您的要求,因此您必须手动进入和退出范围。如果您可以管理它们,那么框架将保证每个范围的范围依赖项的唯一实例