如何注入没有注释Spring类的对象

时间:2017-12-09 09:52:29

标签: spring javafx

假设我有一个JavaFx类和一个ViewState类,它需要在start方法中创建stage的referance。我怎么能自动装配这样的依赖?我知道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

1 个答案:

答案 0 :(得分:2)

您可能根本不想这样做:您的ViewState类似乎是某种类型的模型类,因此它不应该引用UI元素(例如{{1 }}为s)。

但是,为了完整起见,这是一个有效的示例,使用Stage。请注意,由于您无法在注册阶段之前创建ConfigurableApplicationContext.getBeanFactory().registerResolvableDependency(...)对象,因此您需要创建View bean View

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