Managed Bean的创建与初始化
1.Managed Bean 被定义在faces-config.xml里,当这个Bean第一次被引用时就会被初始化,
它的生存周期由<managed-bean-scope>XXX</managed-bean-scope>来决定,
<managed-bean>
<managed-bean-name>user</managed-bean-name>
<managed-bean-class>org.examples.TestBean</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
<managed-property>
<property-name>id</property-name>
<value>111</value>
</managed-property>
<managed-property>
<property-name>name</property-name>
<value>gembin</value>
</managed-property>
</managed-bean>
这里其实用了反转控制(Inversion
of Control, IoC) type 2, 即通过Setter注入,具体可参考Fowler, Dependency Injection这本书。假如你需要当Application Startup的时候就要初始化一些Bean(例如建立数据库连接,因为它的初始化需要1段时间),这就需要加ServletContextListener。
2.声明Lists and Maps作为managed
beans
这里managed-bean-class必须是个实现类,而不能是List 或者Map,因为他们是接口,不能被初始化.
并且用<list-entries>和<map-entry>代替<managed-property>
<managed-bean>
<description>List
of favorite sites</description>
<managed-bean-name>favoriteSites</managed-bean-name>
<managed-bean-class>java.util.ArrayList</managed-bean-class>
<managed-bean-scope>application</managed-bean-scope>
<list-entries>
<value>http://www.jsfcentral.com</value>
<value>http://www.theserverside.com</value>
<value>http://www.ibm.com/developerworks/</value>
<value>http://otn.oracle.com</value>
<value>http://www.java.net</value>
<value>http://www.manning.com</value>
</list-entries>
</managed-bean>
<managed-bean>
<description>List
of favorite sites, keyed by name.</description>
<managed-bean-name>favoriteSitesMap</managed-bean-name>
<managed-bean-class>java.util.HashMap</managed-bean-class>
<managed-bean-scope>application</managed-bean-scope>
<map-entries>
<map-entry>
<key>JSF
Central</key>
<value>http://www.jsfcentral.com</value>
</map-entry>
<map-entry>
<key>TheServerSide.com</key>
<value>http://www.theserverside.com</value>
</map-entry>
<map-entry>
<key>IBM
DeveloperWorks</key>
<value>http://www.ibm.com/developerworks/</value>
</map-entry>
<map-entry>
<key>Oracle
Technology Network</key>
<value>http://otn.oracle.com</value>
</map-entry>
<map-entry>
<key>java.net</key>
<value>http://www.java.net</value>
</map-entry>
<map-entry>
<key>Manning
Publications</key>
<value>http://www.manning.com</value>
</map-entry>
</map-entries>
</managed-bean>
3.
用value-binding expressions引用managed
beans
假如有如下Beans
<managed-bean>
<description>test</description>
<managed-bean-name>user</managed-bean-name>
<managed-bean-class>org.examples.UserBean</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
<managed-bean>
<managed-bean-name>referer
</managed-bean-name>
<managed-bean-class>org.examples.Referer</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
<managed-property>
<property-name>user</property-name>
<value>#{user}</value>
</managed-property>
</managed-bean>
这里referer用value-binding expressions引用了user,但是引用是不能循环的,即user不能在反过来引用referer,由此可见用value-binding expressions是相当的灵活阿,哈哈
To be continued....