2011-04-11 88 views
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要求是相同的。嗯...

+0

您正在尝试在@PostConstruct中使用注入值。我不知道第一个会发生什么 - @ManagedProperty注入或@PostConstruct。你检查过了吗? – Osw 2011-04-11 20:06:34

+0

@Osw:@ @ PostConstruct在所有依赖注入之后运行,所以这部分是好的。 – BalusC 2011-04-11 22:05:28

+0

@BalusC:根据DI和'@ PostContruct'文档,您是正确的。尽管如此,我不确定为什么我要'null'而不是'5148'。这很奇怪! – ChuongPham 2011-04-12 04:13:10

回答

2

我刚刚在我的一个托管的bean中尝试了这个,它正在工作。这里是相关的代码,它基本上和你的一样:

@ManagedBean 
@RequestScoped 
public class TestBean { 
    @ManagedProperty(value = "#{param.id}") 
    private Long prop; 

    @PostConstruct 
    public void init() { 
     System.out.println(prop); 
     // prints 1234 if I go to the url with http://localhost/page.jsf?1234 
    } 

    public Long getProp() { 
     return prop; 
    } 

    public void setProp(Long prop) { 
     this.prop = prop; 
    } 
} 

我在glassfish 3.1.1上运行这个。我唯一的想法可能是注入的EJB在某种程度上搞乱了ManagedBean中的请求范围?