2
我有这样的服务豆:@ManagedProperty注释类型返回null
@Stateless
public class BookService
{
@PersistenceContext(unitName="persistentUnit")
protected EntityManager entityManager;
public BookModel find(Long id) {
return entityManager.find(BookModel.class, id);
}
}
而且支持Bean的facelet页:
@ManagedBean(name = "bookBean")
@RequestScoped
public class BookBean implements Serializable
{
@EJB
private BookService bookService;
@ManagedProperty(value="#{param.id}")
private Long id;
private DataModel<BookModel> books;
private BookModel currentBook;
@PostConstruct
public void init() {
if (id == null) {
// UPDATE: Retrieve a list of books.
} else {
// UPDATE: id shouldn't be null here.
// Get detail info about a book using the id
currentBook = bookService.find(id);
}
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public BookModel getCurrentBook() {
return currentBook;
}
public void setCurrentBook(BookModel currentBook) {
this.currentBook = currentBook;
}
}
为什么是id
值总是返回null即使URL返回为bookedit.jsf?id=5418
我不明白这一点。
另外,我发现EntityManager#find
方法的限制性很强,因为它只接受主键值作为第二个参数。如果我想传递[哈希]值而不是主键,该怎么办?我如何用EntityManager#find
方法做到这一点?
P.S.我注意到OpenJPA和EclipseLink实现的EntityManager#find
要求是相同的。嗯...
您正在尝试在@PostConstruct中使用注入值。我不知道第一个会发生什么 - @ManagedProperty注入或@PostConstruct。你检查过了吗? – Osw 2011-04-11 20:06:34
@Osw:@ @ PostConstruct在所有依赖注入之后运行,所以这部分是好的。 – BalusC 2011-04-11 22:05:28
@BalusC:根据DI和'@ PostContruct'文档,您是正确的。尽管如此,我不确定为什么我要'null'而不是'5148'。这很奇怪! – ChuongPham 2011-04-12 04:13:10