【发布时间】: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() 时它会抛出错误