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



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

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

B和C也是如此。

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

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

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

有没有任何方法可以将Google Guice用于此目的或其他框架用于此目的?

谢谢!

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

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。

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

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

现在我们可以使用创建"预订流">

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

完整的例子作为要点。

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

您研究过Guice自定义作用域吗?

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

最新更新