tags:

views:

582

answers:

4

I have a backing bean, and I'd like to load up a few lists when the bean is instantiated, so that the list may be used in a dropdown.

Is there a method that only gets called when the bean is first made?

+1  A: 

You could use a static initializer:

static {
   //set up lists
}

Or if they aren't static lists then an initializer block:

{
   //set up lists
}

Tutorial here.

EDIT* Remember that these backing beans are just POJOs and work like any other Java object. You can set up faces-config.xml like such:

<managed-bean-class>mymanagedBean.ConstructorName</managed-bean-class>

Personally I find it easier to just us an initializer block. That's what they are for.

amischiefr
thanks, i appreciate it
bmw0128
A: 

If you want a purely declarative list of values, the faces-config.xml offers some options:

  <managed-bean>
    <managed-bean-name>staticListOfStuff</managed-bean-name>
    <managed-bean-class>java.util.ArrayList</managed-bean-class>
    <managed-bean-scope>application</managed-bean-scope>
    <list-entries>
      <value>Value 1</value>
      <value>Value 2</value>
    </list-entries>
  </managed-bean>

This stuff is covered in section 5.3 The Managed Bean Facility of the JSF 1.2 spec.

McDowell
+3  A: 

Another method is to use the @PostConstruct attribute to have a method do the initializing for you once Spring/JSF has made the bean for you.

Eg:

@PostConstruct
public void init()
{
 List<SelectItem> list = new ArrayList<SelectItem)();
 list = getService().getMenuItems();
 setMenuItems( list );
}
Martlark
i'll try this, looks like it will do the job, thx!
bmw0128
A: 

The JSF-y way of doing this is to bind a PhaseListener to the <f:view>, make your bean implement PhaseListener, then in the implementation methods populate the bean at the required stage.

jeyoung