【问题标题】:NullPointerException when using @Inject Annotation in JavaEE在 JavaEE 中使用 @Inject 注解时出现 NullPointerException
【发布时间】:2020-10-31 17:23:38
【问题描述】:

我有以下服务等级:

@Singleton
public class QuotesLoaderBean {

Properties quotes;
Properties names;
@Inject
public QuoteRepository repo;

public QuotesLoaderBean() {
}

@PostConstruct
public void init() {
    InputStream quotesInput = this.getClass().getClassLoader().getResourceAsStream("quotes.properties");
    InputStream namesInput = this.getClass().getClassLoader().getResourceAsStream("names.properties");

    quotes = new Properties();
    names = new Properties();
    try {
        quotes.load(quotesInput);
        names.load(namesInput);
    } catch (IOException ex) {
        Logger.getLogger(QuotesLoaderBean.class.getName()).log(Level.SEVERE, null, ex);
    }
}

public Citation createCitation(String quote) {
    Citation citation = new Citation();
    citation.setQuote(quote);
    citation.setWho(getName());
    repo.save();
    return citation;
}

public Citation getCitation() {
    Citation citation = new Citation();
    citation.setQuote(getQuote());
    citation.setWho(getName());
    return citation;
}

public String getQuote() {
    Enumeration keys = quotes.propertyNames();
    int elementNumber = new Random().nextInt(quotes.keySet().size());
    return quotes.getProperty(getElement(keys, elementNumber));
}

public String getName() {
    Enumeration keys = names.propertyNames();
    int elementNumber = new Random().nextInt(names.keySet().size());
    return names.getProperty(getElement(keys, elementNumber));
}

private String getElement(Enumeration keys, int elementNumber) {
    int i = 0;
    while (keys.hasMoreElements()) {
        if (i == elementNumber) {
            return (String) keys.nextElement();
        } else {
            i++;
            keys.nextElement();
        }
    }
    return null;
}
}

Repository 类对于测试来说非常简单:

@Singleton
public class QuoteRepository {

public String save() {
    Gson gson = new GsonBuilder().create();
    return "Saved...";
}

}

当我测试 createCitation 方法时,我总是得到 NullPointerException,但我不知道为什么。某些东西不适用于 Injection。我还有一个用@Stateless 注释的api 类,在那里我可以很容易地用@Inject 注释注入服务类。

【问题讨论】:

  • 您是否尝试过使用调试器单步执行此代码?你至少应该能够告诉我们它在哪里投掷。
  • 当我调用 repo.save() 时它会抛出错误

标签: java cdi java-ee-8


【解决方案1】:

当我测试 createCitation 方法时,我总是得到 NullPointerException

您不能简单地测试您的应用程序,因为您将创建对象的责任委托给了在单元测试中(我假设您使用它)不存在的容器。

public Citation createCitation(String quote) {
    Citation citation = new Citation();
    citation.setQuote(quote);
    citation.setWho(getName());
    repo.save(); // repo isn't initialized
    return citation;
}

如果您想测试您的代码,请模拟 repo 对象或使用集成测试。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-27
    • 2015-01-11
    • 2017-09-09
    • 2013-04-30
    • 1970-01-01
    • 2013-08-03
    • 1970-01-01
    相关资源
    最近更新 更多