【问题标题】:Spring application context is nullSpring 应用程序上下文为空
【发布时间】:2016-08-27 09:07:52
【问题描述】:

我正在使用带有 JavaFX 的 Spring Boot 1.3.3。应用程序成功启动启动画面(此时 applicationContext 不为空)

@SpringBootApplication
public class PirconApplication extends Application{

@Bean(name = "primaryStage")
public Stage getPrimaryStage() {
    return new Stage(StageStyle.DECORATED);
}

private ConfigurableApplicationContext applicationContext = null;
private static String[] args = null;

@Override
public void stop() throws Exception {
    super.stop();
    Platform.exit();
    applicationContext.close();
}

@Override
public void start(Stage primaryStage) throws Exception {
    Task<Object> worker = worker();
    worker.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
        @Override
        public void handle(WorkerStateEvent event) {
            try {
                AppSplashController loader = applicationContext.getBean(AppSplashController.class);
                Stage stage = applicationContext.getBean(Stage.class);
                stage.setScene(loader.init());
                stage.initStyle(StageStyle.UNDECORATED);
                stage.show();
            } catch (IOException e) {
                    e.printStackTrace();
                    System.exit(0);
            }
        }
    });
    worker.setOnFailed(new EventHandler<WorkerStateEvent>() {

            @Override
            public void handle(WorkerStateEvent event) {
                    // TODO Auto-generated method stub
                    System.exit(0);
            }
    });
    worker.run();
}
public static void main(String[] args) {
    PirconApplication.args = args;
    launch(PirconApplication.class, args);
}

private Task<Object> worker() {
    return new Task<Object>() {
        @Override
        protected Object call() throws Exception {
                applicationContext = SpringApplication.run(PirconApplication.class, args);
                return null;
        }
    };
}
}

问题出在 AppSplashController applicationContext 和 primaryStage bean 都为空。

@Component
public class AppSplashController implements BootInitializable {

@FXML
private ImageView imgLoading;
@FXML
private Text lblWelcome;
@FXML
private Text lblRudy;
@FXML
private VBox vboxBottom;
@FXML
private Label lblClose;

private Stage primaryStage;

private ApplicationContext springContainer;
/**
 * Initializes the controller class.
 */
@Override
public void initialize(URL url, ResourceBundle rb) {
    System.out.println("applicationContext: "+springContainer);
    System.out.println("primaryStage: "+primaryStage);
}

}

@Autowired
@Override
public void setPrimaryStage(Stage primaryStage) {
    this.primaryStage = primaryStage;
}

@Override
public Scene init() throws IOException {
    Parent root = FXMLLoader.load(getClass().getResource("/com/pircon/views/splash.fxml"));
    return new Scene(root);
}

@Override
public void setApplicationContext(ApplicationContext ac) throws BeansException {
    this.springContainer = ac;
}

}

BootInitializable 接口

public interface BootInitializable extends Initializable, ApplicationContextAware {
    public Scene init() throws IOException; 
    public void setPrimaryStage(Stage primaryStage);
}

这是我在spring和spring boot中的第一个项目,请原谅我的无知。

【问题讨论】:

标签: java spring javafx spring-boot


【解决方案1】:

我认为您需要指定 spring 来设置这些 bean 的自动装配。例如

@Autowired
private ApplicationContext springContainer;

另一个建议是使用实现springs ApplicationContextAware 接口的ApplicationContextProvider。

public class ApplicationContextProvider implements ApplicationContextAware {
    private static ApplicationContext context;

    public static ApplicationContext getApplicationContext() {
        return context;
    }

    @Override
    public void setApplicationContext(ApplicationContext ctx) {
        context = ctx;
    }
}

您可以通过ApplicationContextProvider.getApplicationContext();获取应用上下文

【讨论】:

  • 注意:由于没有提供此问题的完整上下文,因此此答案基于提到 bean 为空的评论。
  • 尝试添加自动装配注释,但在我 system.out 时仍然返回 null。上下文是应用程序能够加载视图,尽管问题出在视图(fxml)的控制器中,但我无法访问 primaryStage 和 springContainer
  • 另一个建议是使用实现 ApplicationContextAware 的 ApplicationContextProvider。将更新答案。
  • 能否在此修复后添加完整代码?我希望您正在尝试在后期构造中获取上下文。
  • 我使用完全相同的 ApplicationContextAware 但我的 applicationContext 为空。
【解决方案2】:

这是在应用程序级别方便使用 ApplicationContext 实例的另一种方法。

import org.springframework.context.ApplicationContext;

/**
 * @author Dinesh.Lomte
 *
 */
public enum AppContext {

    INSTANCE;

    public static AppContext getInstance() {
        return INSTANCE;
    }

    private ApplicationContext applicationContext;

    /**
     * Default constructor
     */
    private AppContext() {      
    }

    /**
     * 
     */
    public void setContext(ApplicationContext applicationContext) {     
        this.applicationContext = applicationContext;
    }

    /**
     * 
     * @return
     */
    public ApplicationContext getContext() {
        return applicationContext;
    }
}

在服务器启动或应用程序启动期间设置 ApplicationContext 实例。

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;

import com.app.logger.AppLogger;
import com.app.util.AppContext;

/**
 * @author Dinesh.Lomte
 *
 */
@SpringBootApplication
@ComponentScan ({"com.app"})
public class RunSpringApplication {

    private static final AppLogger LOGGER = 
            new AppLogger(RunSpringApplication.class); 

    /**
     * @param args
     */
    public static void main(String[] args) {
        ApplicationContext applicationContext = SpringApplication.run(
                RunSpringApplication.class, args);
        // Setting the application context for further references 
        AppContext.getInstance().setContext(applicationContext);

        LOGGER.info("------------------------------------------------");
        LOGGER.info("App started successfully.");                   
    }
}

最后根据需要在类中使用 ApplicationContext 实例。

ApplicationContext applicationContext = AppContext.getInstance().getContext();      
AppConfigProp appConfigProp = applicationContext.getBean(AppConfigProp.class);

MailConfigProp mailConfigProp = AppContext.getInstance().getContext()
            .getBean(MailConfigProp.class);

【讨论】:

    猜你喜欢
    • 2016-05-20
    • 2019-08-13
    • 2010-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-13
    • 2013-02-06
    • 2014-07-24
    相关资源
    最近更新 更多