Thursday, February 10, 2011

Faces Backing Bean initializing

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?

  • 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.

    bmw0128 : thanks, i appreciate it
    From amischiefr
  • 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.

    From McDowell
  • 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 );
    }
    
    bmw0128 : i'll try this, looks like it will do the job, thx!
    From Martlark
  • 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.

    From jeyoung

0 comments:

Post a Comment