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

时间:2011-08-15 07:23:55

标签: java jsf javabeans faces-config

我有一个名为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作为值。

感谢Advanced~

3 个答案:

答案 0 :(得分:2)

假设属性文件与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设置器中调用它,或者在bundlePropertiesMap getter中执行延迟检查。

答案 1 :(得分:1)

你可以使用具有更高级依赖注入机制的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>

答案 2 :(得分:0)

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