java - JavaFX 中 Spring Autowiring 的空指针异常

标签 java spring javafx

我正在尝试使用 Autowired 注释将我的数据模型类 Autowiring 到各种 Controller 类中,但我不断收到空指针异常,我希望保持我的配置基于 XML,并尽可能避免使用应用程序上下文实现。下面是代码片段和 spring-config 文件

Spring 配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-2.5.xsd">

    <context:annotation-config/>

    <bean id="datamodel" class="com.filemanager.datamodel.DataModel" autowire="byType"/>

</beans>

数据模型类

public class DataModel {

    private ObservableList<Song> windowDisplaySongs;

    public void test() {
        System.out.println("Hey, this is working");
    }

    public ObservableList<Song> getWindowDisplaySongs() {
        return windowDisplaySongs;
    }
    public void setWindowDisplaySongs(ObservableList<Song> windowDisplaySongs) {
        this.windowDisplaySongs = windowDisplaySongs;
    }
}

依赖于模型的 Controller

public class FileBrowserController implements Initializable {

    @Autowired
    DataModel dataModel;

    @Override
    public void initialize(URL location, ResourceBundle resources) {

        dataModel.test();
    }
}

我尝试过的事情

  • 在模型类上方以及模型和 Controller 类上方使用组件注释

  • 在 Controller 类上方使用 Controller 注解

  • 重命名数据模型引用以匹配 spring-config 文件中的名称

  • 使用限定符注释指定数据模型引用应与 Spring 配置文件中的名称匹配。

  • 在 init 方法以外的方法中使用模型引用

  • 从配置文件中删除 autowire="byType"

  • 使用下面的代码在 main 方法中创建应用程序上下文,我能够使用 getBean() 方法,但我想使用 autowired 自动注入(inject)依赖项,而不必调用每次都调用 getBean() 方法。

    ApplicationContext ctx = new ClassPathXmlApplicationContext("config/spring-config.xml");
    
  • 遵循 Stackoverflow 上已有的其他空指针 spring 问题的解决方案:

最佳答案

FileBrowserController 类应该被注释为 @Controller,这样 spring 就知道它应该在那里注入(inject)属性。另外,不带限定符的 @Autowiring 会检查您是否有带有属性名称的 bean。对于您的情况:

@Autowired
DataModel dataModel;

检查 id dataModel 的 bean,但您的 bean 是用不同的名称定义的:

<bean id="datamodel"...

发现区别了吗? :) 您可以更改 bean id,也可以使用 Qualifier 使其更加清晰

@Autowired
@Qualifier("datamodel")
DataModel dataModel;

关于java - JavaFX 中 Spring Autowiring 的空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49770466/

相关文章:

java - 如何为开发和生产环境使用不同的 META-INF/context.xml 文件

java - 使用 net.sourceforge.jtds.jdbc.Driver 连接 SpringMVC 与 JDBC 时出错

javafx - 如何在JavaFX的MenuButton中创建子菜单?

java - 将变量传递到javafx中的不同场景

JavaFX 表格 View : Do I HAVE to wrap my fields in Simple<Object/Integer/String>Property?

java - 我如何转换字符串以将其实现为数据库字段 - Java/Spring/Postgres?

java - spring war 文件部署到 tomcat 9 但没有正确重定向?

java - 从 Grails Controller /服务获取 OpenID URL

java - 如何在 Spring MVC 中设置系统属性

java - 从 Spring Boot 持续使用 REST Web 服务