使用faces-config.xml初始化JSF bean



我有一个名为Bucket的Bean,它有一个HashMap。我想初始化bean,并用一个属性文件填充faces-config.xml中的HashMap。我该怎么做呢?

豆:

public class BundleBean {
 private Map<String, String> bundlePropertiesMap = new HashMap<String, String>();
 private String bundleFileName;
 // Setter, getter goes here....
}

属性文件,命名为bundle.properties,并且它位于类路径中。

bucket.id=DL_SERVICE

faces-config.xml文件:

<managed-bean>
    <description>
        Java bean class which have bundle properties.
    </description>
    <managed-bean-name>bundleBean</managed-bean-name>
    <managed-bean-class>org.example.view.bean.BundleBean</managed-bean-class>
    <managed-bean-scope>application</managed-bean-scope>
    <managed-property>
        <property-name>bundleFileName</property-name>
        <value>bundle.properties</value>
    </managed-property>
</managed-bean>

Map必须有bucket。id作为键,DL_SERVICE作为值。

Thanks in Advanced~

假设属性文件与BundleBean处于相同的ClassLoader上下文中,则调用如下方法:

@SuppressWarnings("unchecked")
private void loadBundle(String bundleFileName, Map<String, String> map)
                                                         throws IOException {
    InputStream in = BundleBean.class.getResourceAsStream(bundleFileName);
    try {
        Properties props = new Properties();
        props.load(in);
        ((Map) map).putAll(props);
    } finally {
        in.close();
    }
}

最好使用@PostConstruct注释调用。如果这不是一个选项,则在bundleFileName setter中调用它,或者在bundlePropertiesMap getter中执行惰性检查。

您可以使用具有更高级依赖注入机制的spring。当您将spring与jsf集成时,您可以在spring上下文中定义jsf bundlebean

<bean id="injectCollection" class="CollectionInjection">
        <property name="map">
            <map>
                <entry key="someValue">
                    <value>Hello World!</value>
                </entry>
                <entry key="someBean">
                    <ref local="oracle"/>
                </entry>
            </map>
        </property>

如果我没有弄错的话,JSF在初始化bean时调用相应的setter。因此,提供一个方法public void setBundleFileName(String filename)应该工作。

最新更新