开发者

JavaServer Faces Bean instantiation order

Are there any guarantees about the order in which JSF creates its managed beans?

My case is pretty much the following: I have 2 beans that I use in the same page. When creating the second one, I want it to get some information from the first, e.g. in its @PostConstruct method (to avoid h开发者_如何学Goitting the database).

Is there any way I can make sure the first bean is actually created before the second, so getting the data succeeds?


You can ensure this by injecting the one bean as a managed property of the other bean.

Assuming that you're already on JSF 2.0, use @ManagedProperty:

@ManagedBean
@RequestScoped
public class FirstBean {
    // ...
}

@ManagedBean
@RequestScoped
public class SecondBean {

    @ManagedProperty(value="#{firstBean}")
    private FirstBean firstBean; // +setter

    @PostConstruct
    public void init() {
        // firstBean is available here.
    }

    // ...
}

Or when you're still on JSF 1.2, use <managed-property> in faces-config.xml:

<managed-bean>
    <managed-bean-name>firstBean</managed-bean-name>
    <managed-bean-class>com.example.FirstBean</managed-bean-class>
    <managed-bean-scope>request</managed-bean-scope>
</managed-bean>

<managed-bean>
    <managed-bean-name>secondBean</managed-bean-name>
    <managed-bean-class>com.example.SecondBean</managed-bean-class>
    <managed-bean-scope>request</managed-bean-scope>
    <managed-property>
        <property-name>firstBean</property-name>
        <value>#{firstBean}</value>
    </managed-property>
</managed-bean>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜