CDI中@Inject注释的空指针异常

时间:2019-02-05 17:58:25

标签: java nullpointerexception cdi inject

我在我的JavaFX应用程序中集成了CDI并配置ResourceBundle。但不幸的是,在MainView类中,Inject对象具有空指针异常。

这是我的代码:

配置类

@Singleton
public class ResourceProvider {
    @Produces
    private ResourceBundle defaultResourceBundle = ResourceBundle.getBundle("default");
}

入门班:

public class App extends MvvmfxCdiApplication {

    private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(App.class);

    @Inject
    private ResourceBundle resourceBundle;

    public static void main(String... args) {
        Locale.setDefault(Locale.US);
        launch(args);
    }

    @Override
    public void startMvvmfx(Stage stage) throws Exception {
        LOG.info("Starting the Application");
        MvvmFX.setGlobalResourceBundle(resourceBundle);
        ViewTuple<MainView, MainViewModel> viewTuple = FluentViewLoader
            .fxmlView(MainView.class)
            .resourceBundle(resourceBundle)
            .load();

        Parent root = viewTuple.getView();

        stage.setScene(new Scene(root));
        stage.setTitle(resourceBundle.getString("window.title"));

        stage.show();

    }

    public void triggerShutdown(@Observes TriggerShutdownEvent event) {
        LOG.info("Application will now shut down");
        Platform.exit();
    }
}

在入门类中,resourceBundle字段没有问题,但是在MainView类中,空指针异常。

MainView类

public class MainView implements FxmlView<MainViewModel>, Initializable {

    @Inject
    private ResourceBundle resourceBundle; // null pointer is here
    ...
    ...
}

这是我的CDI配置xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
    http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
   bean-discovery-mode="all">

异常消息在这里:

Caused by: java.lang.NullPointerException
at com.arion.contacts_mvvm.ui.main.MainView.<init>(MainView.java:30)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)

我不明白,为什么会出现空指针异常。

0 个答案:

没有答案