简体   繁体   English

类型上的CDI引发NPE

[英]CDI on a type throws NPE

I am trying to understand CDI. 我试图了解CDI。 I have an interface: 我有一个界面:

public interface Person {
    public String getName();
}

And a class that implements Person : 和一个实现Person的类:

public class Male implements Person {
    public Male() {}
    @Override
    public String getName() {
        return "ra";
    }
}

In the main class, I tried: 在主要课程中,我尝试过:

public class Main {
    @Inject
    private Person person;
    public static void main(String... args) {
        System.out.println(new Main().person.getName());
    }
}

but the above code throws NPE on person.getName() . 但是上面的代码在person.getName()上抛出了NPE I created the project using maven and the scope of javaee api is compile . 我使用maven创建了项目,并且javaee api的范围是compile What am I doing wrong? 我究竟做错了什么?

You miss to start a CDI container it seems. 您似乎错过了启动CDI容器的机会。

Note that any annotation on a class is just like a post-it. 请注意,类上的任何注释都类似于便利贴。 It is really only an additional info and not real code. 它实际上只是一个附加信息,而不是真实代码。 This information has to be interpreted. 该信息必须被解释。 This is what the CDI container does. 这就是CDI容器的作用。 I've written up an introduction article to CDI which explains a little bit of the basics: https://jaxenter.com/tutorial-introduction-to-cdi-contexts-and-dependency-injection-for-java-ee-jsr-299-104536.html 我写了一篇关于CDI的介绍文章,其中介绍了一些基础知识: https : //jaxenter.com/tutorial-introduction-to-cdi-contexts-and-dependency-injection-for-java-ee-jsr -299-104536.html

What do you miss: 你错过了什么:

1.) add an empty META-INF/beans.xml file. 1.)添加一个空的META-INF / beans.xml文件。 Or add a scope annotation like @ApplicationScoped to your Male.java class. 或将诸如@ApplicationScoped Male.java类的范围注释添加到Male.java类。

2.) add a CDI container. 2.)添加一个CDI容器。 There are multiple options. 有多种选择。 If you want to use the Apache OpenWebBeans CDI container then you can find some infos here https://openwebbeans.apache.org/owbsetup_se.html You can also find a working sample over here 如果要使用Apache OpenWebBeans CDI容器,则可以在这里找到一些信息https://openwebbeans.apache.org/owbsetup_se.html您也可以在此处找到一个有效的示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM