【问题标题】:ManagedProperty is not availableManagedProperty 不可用
【发布时间】:2014-06-30 18:55:25
【问题描述】:

我有两个 ManagedBeans(SessionHandler 和 OrderHandler)。两者都是会话范围的。

SessionHandler:

@ManagedBean(name="session")
@SessionScoped
public class SessionHandler {

    private Account account;

    public String login() {
        try {
            // ... login method ...

            return("bookinglist.xhtml?faces-redirect=true");
        }
        catch (Exception e) {
            // ... exception handling ...
        }
    }

    // ... getter & setter ...
}

订单处理程序:

@ManagedBean(name="order")
@SessionScoped
public class OrderHandler {

    @ManagedProperty(value="#{session.account}")
    Account account; // getter and setter

    public OrderHandler() {
        this.createList();
    }

    private void createList() {
        // method creates an ArrayList of bookings
        // it uses this.account.getId() for a SQL statement
    }
}

bookinglist.xhtml 我想显示欢迎文本和我的列表:

<p>Welcome, #{sessions.account.name}!</p>

<ui:repeat value="#{order.bookingList}" var="item">
    <!-- ... items ... --->
</ui:repeat>

显示欢迎文本,但我的列表为空,因为在我的 sql 语句中 accountID 为空。 accountID = 1 的语句(例如)有效。在预订过程的后期,我可以使用 accountID(无需重新声明或覆盖它)。

我想问题是,该属性在登录后无法立即使用......但我不知道为什么。有人可以帮我吗?

【问题讨论】:

  • 制作“OrderHandler”@RequestScoped 怎么样?
  • 无效...而且我需要 OrderHandler 为其他方法的 SessionScoped。

标签: jsf managed-bean myfaces


【解决方案1】:

使用@ManagedProperty 时,要记住的一个重要事实是,一旦 bean 构造函数被调用后,此类属性将被注入。原因是因为 JSF 只能在 bean 完全构造时注入一个属性。

实际上,这意味着,从您当前的代码中,account 将在调用 createList() 之后被注入。如果你调试OrderHandler,你很可能会看到如下执行顺序:

// bean instantiation step
-> OrderHandler constructor called
   -> createList called

// bean property injection step
-> Account injected

要解决这个问题,你需要在构造函数完成后调用createList(),并且account已经被注入。您可以使用带有@PostConstruct 注释的方法来实现:

@PostConstruct
private void init() {
    // this will be called after constructor call, and property injection
    this.createList();
}

您可以在此处阅读有关@PostConstruct 注释的更多信息:

http://docs.oracle.com/javaee/7/api/javax/annotation/PostConstruct.html

【讨论】:

    猜你喜欢
    • 2013-10-04
    • 1970-01-01
    • 1970-01-01
    • 2011-05-27
    • 2023-03-07
    • 1970-01-01
    • 2013-10-01
    • 2014-01-08
    • 2011-07-29
    相关资源
    最近更新 更多