熟悉 Java EE, Dependency Injection and JPA, Hibernate 的请帮忙看看。
为什么调试总显示第二个类 Word 里面的这行有 NullPointerException??
Term term = repository.findById(id);
repository 为 null.
也就是这行
@Inject
private Repository repository;
并没有 Inject 成功. 错在哪里?
Class 1: Repository.java:
@ApplicationScoped
public class Repository {
@Inject
private EntityManager em;
public Term findById(Long id) {
return em.find(Term.class, id);
}
}
Class 2: Word.java
@Named
@RequestScoped
public class Word {
@Inject
private Logger log;
@Inject
private Repository repository;
private Term term;
public Word() {
}
public Word(Long id) {
try{
term = this.findTermById(id);
}catch(Exception e) {
e.printStackTrace();
}
}
@Produces
@Named
public Term getTerm() {
return term;
}
public Term findTermById(Long id) {
Term term = repository.findById(id);
if(term==null) {
log.info("Can't find this word from database: " + term);
}
return term;
}
}
Class 3: Resources.java
public class Resources {
@Produces
@PersistenceContext
private EntityManager em;
@Produces
public Logger produceLog(InjectionPoint injectionPoint) {
return Logger.getLogger(injectionPoint.getMember().getDeclaringClass
().getName());
}
@Produces
@RequestScoped
public FacesContext produceFacesContext() {
return FacesContext.getCurrentInstance();
}
}