How to instantiate a backing bean on page load

1.5k views Asked by At

For a project we are migrating some java applications to WebSphere 8.5. In the process we are trying to get rid of some legacy frameworks. One of them is shale (apache attic). The only component from shale that is used is the view controller to instantiate a request scoped jsf managed beans for every page. Every bean has an init method that is called on page load. I'd like to use @PostConstruct on this method. The only problem I have that the bean gets instantiated when a method on the bean is called. Unfortunately the bean is not always called and the init method does populate data on a session scoped bean. There is a naming convention that links pages and beans so we could use a listener to instantiate the bean based on the request. Another solution might be changing the scope to viewscope (probably to much a hassle on websphere 8.5).

I was wondering if there is something I can do to make the PostConstruct work? And are there other options I'm missing?

edit: I have a PhaseListener in place that performs the basic functionality. It matches the requested page to the corresponding bean (by naming convention). The following is used to instantiate the bean but it looks a bit ugly.

expressionFactory.createValueExpression(elContext, "#{" + managedBeanName + "}", Object.class)

Is there a more elegant way to do this?

2

There are 2 answers

1
MarcD On BEST ANSWER

Perhaps you could try using <f:event/> ?

In your view, you could add this to the page.

<f:event type="postAddToView" listener="#{backingBean.myInitMethod()"/>

https://stackoverflow.com/a/14004230/4706826

Gives you info on when the events get executed.

1
akaine On

Put a @PostConstruct annotated method in the backing bean. This annotation tells the bean to execute the annotated method every time its constructor is being called.

Example:

@ManagedBean
@ViewScoped
public class MyManagedBean{

    @PostConstruct
    public void initView() throws Exception{
        ...initialize page values, execute database queries, etc.
    }