我正在将JavaFX 2与Spring Framework结合使用,但是注入发生得很晚。我的控制器由FXML-Loader实现,该控制器的成员变量的Spring注入工作,但它的工作时间太晚,这意味着在(1)注入但没有发生,并且在(2)注入确实发生:
public class MainController extends AbstractController
{
@Autowired
public StatusBarController statusbarController;
// Implementing Initializable Interface no longer required according to
// http://docs.oracle.com/javafx/2/fxml_get_started/whats_new2.htm:
private void initialize() {
BorderPane borderPane = (BorderPane)getView();
borderPane.setBottom(statusbarController.getView()); // (1) null exception!
}
// Linked to a button in the view
public void sayHello() {
BorderPane borderPane = (BorderPane)getView();
borderPane.setBottom(statusbarController.getView()); // (2) works!
}
}
让Spring注入statusbarController
之前的状态是什么?我不能让用户点击按钮加载我的GUI; - )
我的AppFactory是这样的:
@Configuration
public class AppFactory
{
@Bean
public MainController mainController() throws IOException
{
return (MainController) loadController("/main.fxml");
}
protected Object loadController(String url) throws IOException
{
InputStream fxmlStream = null;
try
{
fxmlStream = getClass().getResourceAsStream(url);
FXMLLoader loader = new FXMLLoader();
Node view = (Node) loader.load(fxmlStream);
AbstractController controller = (AbstractController) loader.getController();
controller.setView(view);
return controller;
}
finally
{
if (fxmlStream != null)
{
fxmlStream.close();
}
}
}
}
答案 0 :(得分:2)
您应该在FXMLLoader上设置一个ControllerFactory,以便您负责创建控制器实例。