Java server faces

Mixing Annotations with faces-config.xml Settings in JSF 2.0

TheServerSide.com

With JavaServer Faces 2.0, we finally see the introduction of a standard, annotation based approach to component development. No longer do your JSF applications need to maintain a long and arduous faces-config.xml file. Instead, you can simply annotate your JavaBeans, and the JSF framework will manage your beans accordingly.

 

So, to have the JSF framework recognize a JavaBean, and manage the lifecycle of that instance, here’s how simple the annotation is:

 

@ManagedBean
public class SuperBean { /* stuff goes in here */}

           

And you can further annotate. So if you wanted the bean to be managed in the request scope, you simply add another annotation:

 

@ManagedBean
@RequestScoped
public class SuperBean { /* stuff goes in here */}  

 

And all of this replaces the need for a faces-config.xml file such as the following:

 

<?xml version='1.0' encoding='UTF-8'?>

<faces-config xmlns="http://java.sun.com/xml/ns/javaee"

     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee

     http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"

     version="2.0">

 <managed-bean>

   <managed-bean-name>superBean</managed-bean-name>

   <managed-bean-class>com.SuperBean</managed-bean-class>

   <managed-bean-scope>request</managed-bean-scope>

  </managed-bean>
</faces-config>

 

Of course, the question always arises as to what happens if you both annotate the POJO, and you have a configuration in the faces-config.xml file. Well, at runtime, the faces-config.xml file trumps any annotations. So, if you have a bean whose behavior you want to change, but you can’t get in and edit the source code, all you have to do is configure a faces-config.xml file, and the corresponding settings will take precedence at runtime.

27 Dec 2010

Disclaimer: Our Tips Exchange is a forum for you to share technical advice and expertise with your peers and to learn from other enterprise IT professionals. TechTarget provides the infrastructure to facilitate this sharing of information. However, we cannot guarantee the accuracy or validity of the material submitted. You agree that your use of the Ask The Expert services and your reliance on any questions, answers, information or other materials received through this Web site is at your own risk.