Search code examples
javajsfjavabeansfaces-config

JSF bean initializing with faces-config.xml


I've a Bean named as Bucket, it has a HashMap. I want to initialize the bean and polulate the HashMap in the faces-config.xml with a property file. How can I do that?

Bean:

public class BundleBean {
 private Map<String, String> bundlePropertiesMap = new HashMap<String, String>();
 private String bundleFileName;

 // Setter, getter goes here....
}

Property file, named as bundle.properties, and it's on the classpath.

bucket.id=DL_SERVICE

faces-config.xml file :

<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>

That Map has to have the bucket.id as the key and DL_SERVICE as the value.

Thanks in Advanced~


Solution

  • Assuming the properties file is in the same ClassLoader context as BundleBean, call a method like this:

    @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();
        }
    }
    

    This is best invoked using the @PostConstruct annotation. If that is not an option, call it either in the bundleFileName setter or perform a lazy check in the bundlePropertiesMap getter.