JSF bean initializing with faces-config.xml
-
19-12-2020 - |
Pregunta
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~
Solución
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.
Otros consejos
you can do that with spring that has a more advanced dependency injection mechanism. when you integrate spring with jsf, you can define your jsf bundlebean in the spring context
<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>
If I'm not mistaken, JSF calls the corresponding setters when initializing the bean. Thus providing a method public void setBundleFileName(String filename)
should work.