Monday, July 02, 2007

JSF Managed Bean Properties and Constructors

I think I keep discovering and forgetting this: don't initialize anything in a managed bean's constructor if you want to use properties from faces-config.xml's values.

For example,

public SimplexBean() throws Exception {
simplexService = new SimpleXServiceServiceLocator()
.getSimpleXExec(new URL(simpleXServiceUrl));

System.out.println("Simplex Bean Created");
}

will NOT use the value for simpleXServiceUrl from faces-config.xml. It will use any value set in the code instead.

To work around this, just do something like make a little method

private void initSimplexService() throws Exception {
simplexService = new SimpleXServiceServiceLocator()
.getSimpleXExec(new URL(simpleXServiceUrl));
}

and call it before you invoke the web service. I assume on the scale of things, this is a cheap call, so no need to put it in the constructor even if it is redundant.

Make sure of course that you have get/setSimpleXServiceUrl() methods.

1 comment:

Unknown said...

YOu can also use a @PostConstruct annotation, to have your init function called by the JSF framework upon instantiation allowing you to use a managed-property tag in faces-config.xml