我仍在与我的问题作斗争。我想使用 Spring Framework 来注入依赖项,并且必须使用 Spring boot 来集成两者。
不幸的是,在第一个视图中,自动装配运行正确,但如果我进入下一个阶段,我仍然只能Null Pointer Exception
.
那是主要课程:
@SpringBootApplication(scanBasePackages = "boxingchallenge")
public class BoxingChallengeApplication extends Application {
public ConfigurableApplicationContext springContext;
private Parent root;
public static Stage stage;
@Override
public void init() throws Exception {
springContext = SpringApplication.run(BoxingChallengeApplication.class);
springContext.getAutowireCapableBeanFactory().autowireBean(this);
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/FXML/start.fxml"));
fxmlLoader.setControllerFactory(springContext::getBean);
root = fxmlLoader.load();
}
@Override
public void start(Stage primaryStage) throws Exception {
stage = primaryStage;
primaryStage.setTitle("Boxing challenge");
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();
}
@Override
public void stop() {
springContext.stop();
}
public static void main(String[] args) {
launch(BoxingChallengeApplication.class, args);
}
}
在第一个控制器类中,自动装配运行得很酷:
@Component
public class Start {
@FXML
public Button loadGame;
@FXML
public Button create;
@Autowired
private Boxer boxer;
public void load(ActionEvent event) {
System.out.println(boxer.getName());
}
//next stage
public void createNew(ActionEvent event) throws IOException {
Parent root = FXMLLoader.load(getClass().getResource("/FXML/creator.fxml"));
BoxingChallengeApplication.stage.setScene(new Scene(root));
}
}
在第二阶段,自动装配不起作用:
@Component
public class Creator {
@FXML
public Button ready;
public TextField nation;
public TextField name;
public Boxer boxer;
/*@Autowired
private ApplicationContext context;*/
@Autowired
public void setBoxer(Boxer boxer) {
this.boxer = boxer;
}
public void createdAndPlay(ActionEvent event) {
if (boxer == null)
System.out.println("boxer is null");
else
System.out.println("Injected correctly");
}
}
谢谢,希望能完结...
@Jewelsea 的评论是正确的:加载时必须设置控制器工厂creator.fxml
。如果您不这样做,则FXMLLoader
只需调用其无参数构造函数即可创建控制器,因此 Spring 对它一无所知,也没有机会注入任何依赖项。
为此,您只需访问ApplicationContext
in Start
,并且您可以注入“众所周知的对象”,其中ApplicationContext
是一个例子,在你的Spring管理的bean中:
@Component
public class Start {
@FXML
public Button loadGame;
@FXML
public Button create;
@Autowired
private Boxer boxer;
@Autowired
private ApplicationContext context ;
public void load(ActionEvent event) {
System.out.println(boxer.getName());
}
//next stage
public void createNew(ActionEvent event) throws IOException {
FXMLLoader loader = new FXMLLoader(getClass().getResource("/FXML/creator.fxml"));
load.setControllerFactory(context::getBean);
Parent root = loader.load();
BoxingChallengeApplication.stage.setScene(new Scene(root));
}
}
顺便说一句,当您加载 FXML 文件时,您几乎肯定需要任何控制器的新实例,因此您应该创建任何控制器prototype
scope.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)