【问题标题】:@ManagedProperty annotated type returns null@ManagedProperty 注释类型返回 null
【发布时间】:2011-08-03 08:42:00
【问题描述】:

我有这个服务 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 方法非常严格,因为它只接受主键值作为第二个参数。如果我想传递一个 [hashed] 值而不是主键怎么办。如何使用EntityManager#find 方法做到这一点?

附:我注意到EntityManager#find 的要求对于 OpenJPA 和 EclipseLink 实现是相同的。嗯……

【问题讨论】:

  • 您正在尝试在@PostConstruct 中使用注入值。我不确定首先会发生什么——@ManagedProperty 注入或@PostConstruct。你检查了吗?
  • @Osw: @PostConstruct 在所有依赖注入之后运行,所以这部分没问题。
  • @BalusC:根据 DI 和 @PostContruct 的文档,您是正确的。不过,我不确定为什么我得到null 而不是5148。很奇怪!
  • 代码看起来不错。这可能是一个错字或一些疏忽。我将开始在构造函数/postconstruct 中调试请求参数映射。探索ExternalContext#getRequestParameterMap() 以查看参数是否存在。
  • 真的可以使用#{param.id}来引用参数吗?您不必将参数绑定到 managedbean 的属性并从那里读取吗?

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


【解决方案1】:

我刚刚在我的一个托管 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 中的请求范围?

【讨论】:

    猜你喜欢
    • 2013-11-03
    • 1970-01-01
    • 2017-02-10
    • 1970-01-01
    • 2016-09-09
    • 1970-01-01
    • 1970-01-01
    • 2022-11-15
    • 2018-12-15
    相关资源
    最近更新 更多