I need some advice on design choices available managed bean initiallization:
My managed bean backs a JSF page that has both user input fields and Lists which drive the drop down choices presented to user.
I'm populating the List values and initial user values from DB in the constructor of the Managed Bean. (I can also use @PostConstruct but its the same thing expect I can throw exceptions in the constructor).
Now when the page is submitted, JSF creates a new Bean instance. So the initialization code gets invoked in constructor again.
Here are my issues:
1. Initializing list values again: This is OK since page might need to be rendered again if it contains validation errors, so List data will be needed. However if no validation errors then the initializing Lists is a wasted call.
2. Initializing user values from DB: On submit reading user values from DB is a waste since they will be over-written by FORM values.
Can someone tell me how issues 1 and 2 above are handled ? Is this the standard way of Managed bean initialization( i.e. in bean Constructor or using @PostConstruct).
Appreciate if you can give clear details on Managed bean initialization choices.
It's not really all that good of an idea to do database stuff in a JSF bean constructor. Since JSF beans are constructed using the no-arguments constructor, the only way to get a database connection is to reach out and grab it, and that violates the Inversion of Control (IoC) approach that JSF promotes. Using @PostConstruct, you can inject in a persistency mechanism from outside. Which aside from being ideologically pure makes it easier to set up unit tests.
It sounds like you're reading detail information in, even though you may not intend to use it. Don't bother. I normally invoke an "init()" method to clear out reusable beans or initialize from a constructor (and/or @PostConstruct) for short-scope beans. The init() method is usually invoked from constructor or @PostConstruct and by lead-in action methods (such as beginAdd/beginEdit()).
For long-term properties, consider supplying them in long-term beans. For example, I have apps where the selection menus are mostly constant and are the same for all users. Rather than create and destroy them every time, I create them in a separate bean that has application scope. One trip to the database, one build operation, one copy of the data, many uses.
An IDE is no substitute for an Intelligent Developer.