l******0 发帖数: 244 | 1 熟悉 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();
}
} |
h**********c 发帖数: 4120 | 2 全是你自己写的吗?
为什么不照开源测试集里的例子改改,成功性高一些 |
l******0 发帖数: 244 | 3 Where to find "开源测试集里的例子"? Thanks.
【在 h**********c 的大作中提到】 : 全是你自己写的吗? : 为什么不照开源测试集里的例子改改,成功性高一些
|
w**z 发帖数: 8232 | 4 用 spring 吧。
【在 l******0 的大作中提到】 : Where to find "开源测试集里的例子"? Thanks.
|
i**w 发帖数: 883 | 5 问这种问题,至少说一下哪种jee server呀: jboss, glassfish 还是weblogic? 还有
版本。你不会把这code放tomcat上跑吧 |
h**********c 发帖数: 4120 | 6 下spring或hibernate的源代码,然后解压看folder structure,一般这个级别的开源
库都标配doc,和test folder,里面都有全套的unit tests和integration tests.
这是你从c#和iis得不到的。
我老的advice bundled/smuggled with my opinion. what you get beyond wat u c.
【在 l******0 的大作中提到】 : Where to find "开源测试集里的例子"? Thanks.
|
l******t 发帖数: 55733 | 7 @Inject是哪家的?这应该是容器的问题。context没load上来 |
l******0 发帖数: 244 | 8 Jboss.
【在 l******t 的大作中提到】 : @Inject是哪家的?这应该是容器的问题。context没load上来
|
l******0 发帖数: 244 | 9 dependency injection 应该都差不多吧?
【在 w**z 的大作中提到】 : 用 spring 吧。
|
l******0 发帖数: 244 | 10 谢谢
【在 h**********c 的大作中提到】 : 下spring或hibernate的源代码,然后解压看folder structure,一般这个级别的开源 : 库都标配doc,和test folder,里面都有全套的unit tests和integration tests. : 这是你从c#和iis得不到的。 : 我老的advice bundled/smuggled with my opinion. what you get beyond wat u c.
|
l******0 发帖数: 244 | 11 原来问题是 Word constructor 里面使用了 Repository, 而这时 Repository 还没有
注入,自然为 null. 所以不能在 managed bean 的 constructor 里面使用依存的
object, 因为尚没有注入。 |