如何注入未注释Spring类的对象
假设我有一个JavaFx类和一个ViewState类,需要在start方法中创建如何注入未注释Spring类的对象,spring,javafx,Spring,Javafx,假设我有一个JavaFx类和一个ViewState类,需要在start方法中创建stage的引用。我如何能够自动关联这种依赖关系?我知道Stage.class没有注释为@Component,因此Spring无法检测到duch@Bean @SpringBootApplication @ComponentScan({"controller","service","dao","javafx.stage.Stage"}) @EntityScan( basePackages = {"Model"}) @I
stage
的引用。我如何能够自动关联这种依赖关系?我知道Stage.class
没有注释为@Component
,因此Spring无法检测到duch@Bean
@SpringBootApplication
@ComponentScan({"controller","service","dao","javafx.stage.Stage"})
@EntityScan( basePackages = {"Model"})
@Import({ SpringConfig.class})
public class JavaFXandSpringBootTestApplication extends Application{
private ApplicationContext ctx;
public static void main(String[] args) {
launch();
}
@Override
public void start(Stage stage) throws Exception {
ViewState viewState = ctx.getBean(ViewState.class);
}
ViewState类:
@Componenet
public class ViewState {
@Autowired
private ApplicationContext ctx;
private Stage stage;
@Autowired
public ViewState(Stage stage)
{
this.stage = stage;
}
}
编译器按摩:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'javafx.stage.Stage' available: expected at least 1
您可能根本不想这样做:您的
ViewState
类似乎是某种模型类,因此它不应该引用UI元素(例如Stage
s)
不过,为了完整起见,下面是一个使用ConfigurableApplicationContext.getBeanFactory().registerResolvableDependency(…)
的示例。请注意,由于在注册stage之前无法创建视图
对象,因此需要使视图
bean@Lazy
:
package example;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
@Component
@Lazy
public class View {
@Autowired
public View(Stage stage) {
Button close = new Button("Close");
close.setOnAction(e -> stage.hide());
StackPane root = new StackPane(close);
Scene scene = new Scene(root, 400, 400);
stage.setScene(scene);
stage.show();
}
}
package example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import javafx.application.Application;
import javafx.stage.Stage;
@SpringBootApplication
public class Main extends Application {
private ConfigurableApplicationContext ctx ;
@Override
public void start(Stage primaryStage) {
ctx = SpringApplication.run(Main.class);
ctx.getBeanFactory().registerResolvableDependency(Stage.class, primaryStage);
ctx.getBean(View.class);
}
@Override
public void stop() {
ctx.close();
}
public static void main(String[] args) {
launch(args);
}
}