3

I have a navigation managed bean for each user.

and I need it to initialize first before any other bean because a value is required from the bean.

May I know how do I perform that?

I have tried eager="true" but it doesn't work.

any quick and easy solution via faceconfig would be greatly appreciated.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
seesee
  • 1,145
  • 5
  • 20
  • 46

3 Answers3

2

Just perform the desired initialization job in bean's @PostConstruct.

@PostConstruct
public void init() {
    // Here.
}

It'll be invoked when the bean is injected/referenced from another bean for the first time.

The eager=true works only on application scoped beans.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
0

From what I see you should reference the other bean. Let's assume a have a utility class that can pull a bean from the context.

Basically ->

//Bean A
public void doSomething()
{
  String required = Utility.getBeanB().getRequiredValue();
  use(required);
}
...
//Bean B
public String getRequiredValue()
{
  return "Hi, I'm a required value";
}

I have several large web apps that have a "Session Bean" that stores stuff like user preferences, shared objects etc... and this method works perfectly. By using a reference to the bean you eliminate the need to chain the initialization. That method will always DEPEND on the method in the other bean, thus guaranteeing the order of initialization.

There's a variety of ways to access the bean but I usually go through the EL route ->

Get JSF managed bean by name in any Servlet related class

Best of luck, I try to stay "functionally pure" when I can--and I hope that get's a laugh considering the language!

Community
  • 1
  • 1
Daniel B. Chapman
  • 4,647
  • 32
  • 42
0

Here's some cool hax for ya, in case other solutions aren't working for you due to various circumstances...

Let's say I have a class Alpha that I want initialized first:

public class Alpha {
    @PostConstruct
    public void init() {

    }
}

I can put the following method in Alpha:

@ManagedBean(name = "Alpha", eager = true)
public class Alpha {
    public static void requireAlpha() {
        FacesContext context = FacesContext.getCurrentInstance();
        Object alpha = context.getApplication().evaluateExpressionGet(context, "#{Alpha}", Object.class);
        System.out.println("Alpha required: " + alpha.toString());
    }

    @PostConstruct
    public void init() {

    }
}

Then, in any classes that are initializing too early, simply call:

Alpha.requireAlpha();
// ...
// (Code that requires Alpha to be initialized first.)

And if there's a ChildAlpha class that extends Alpha that you really want to be initialized (rather than the parent), make sure to use "ChildAlpha" instead, in both the name="" and the EL Expression ("#{}").

See here for more infos: Get JSF managed bean by name in any Servlet related class

Andrew
  • 5,839
  • 1
  • 51
  • 72