@ManagedProperty注释类型返回null

时间:2011-04-11 19:55:38

标签: jsf-2 ejb-3.0 jpa-2.0 glassfish-3

我有这个服务bean:

@Stateless
public class BookService
{
    @PersistenceContext(unitName="persistentUnit")
    protected EntityManager entityManager;

    public BookModel find(Long id) {
       return entityManager.find(BookModel.class, id);
    }
}

Facelet页面的支持bean是:

@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要求是相同的。嗯...

1 个答案:

答案 0 :(得分: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中的请求范围?