0

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

感谢进阶~

4

3 回答 3

2

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

@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注解来调用它。如果这不是一个选项,请在bundleFileNamesetter 中调用它或在 getter 中执行惰性检查bundlePropertiesMap

于 2011-08-15T09:45:48.897 回答
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>
于 2011-08-15T07:54:46.153 回答
0

如果我没记错的话,JSF 在初始化 bean 时会调用相应的设置器。因此,提供一种方法public void setBundleFileName(String filename)应该可以工作。

于 2011-08-15T07:48:10.397 回答