将 Spring 加载的配置属性传递给 JSF 世界的正确方法



我在 WEB-INF 目录下有一个重复的配置文件,称为 configDEV.properties 和configPRO.properties(一个用于开发环境,另一个用于生产环境)。

由于这些 Spring 声明和这个 Tomcat 启动参数,我加载了正确的文件:

<context:property-placeholder 
        location="WEB-INF/config${project.environment}.properties" />
-Dproject.environment=PRO
(or –Dproject.environment=DEV)

然后,在 servlet 侦听器(称为 StartListener)中,我执行以下操作,以便允许 JSF 在托管 Bean 和 jsp 视图中访问这些属性。(具体来说,我们将使用一个名为cfg.skin.richSelector的属性)。

public class StartListener implements ServletContextListener {
    public void contextInitialized(ServletContextEvent sce) {
        //Environment properties
        Map<String, String> vblesEntorno = System.getenv();
        //Project properties
        String entorno = vblesEntorno.get("project.environment");
        String ficheroPropiedades = "/WEB-INF/config" + entorno + ".properties";
        try {
            Properties props = new Properties();
            props.load(sc.getResourceAsStream(ficheroPropiedades));
            setSkinRichSelector(sc, props.getProperty("cfg.skin.richSelector"));
        } catch (Exception e) {
            //...
        }
    }
    private void setSkinRichSelector(ServletContext sc, String skinRichSelector) {
        sc.setInitParameter("cfg.skin.richSelector", skinRichSelector); 
    }
    public void contextDestroyed(ServletContextEvent sce) {}
}

在 JSF 管理的 Bean 中:

public class ThemeSwitcher implements Serializable {
    private boolean richSelector;
    public ThemeSwitcher() {
        richSelector = Boolean.parseBoolean(
            FacesContext.getCurrentInstance().getExternalContext().getInitParameter("cfg.skin.richSelector"));
        if (richSelector) {
            //do A
        } else {
            //do B
        }
    }
    //getters & setters
}

在 xhtml 页面中:

<c:choose>
    <c:when test="#{themeSwitcher.richSelector}">
        <ui:include src="/app/comun/includes/themeSwitcherRich.xhtml"/>
    </c:when>
    <c:otherwise>
        <ui:include src="/app/comun/includes/themeSwitcher.xhtml"/>
    </c:otherwise>
</c:choose>

所有这些都工作正常,但我想问专家这是否是最合适的方法,或者是否可以以某种方式简化???

提前感谢您的提示和建议

这取决于你使用的是哪个版本的 Spring。如果它恰好是最新的Spring 3.1,你可以利用@Profile

泉源博客

弹簧源参考

属性占位符保留在应用程序上下文中.xml如果你在春豆中使用它。

在您的 Web 中配置上下文初始化参数.xml如下所示:

   <context-param>
      <param-name>envProp</param-name>
      <param-value>${project.environment}</param-value>
   </context-param>

同时将属性文件移动到类路径中的某个包下(注意:由于此更改,您需要使用 classpath*: 前缀在应用程序上下文中查找资源)

然后,您可以在 JSF 页面中加载捆绑包,如下所示:

<f:loadBundle basename="com.examples.config#{initParam['envProp']}" var="msgs"/>

并使用类似这样的东西:

<h:outputText value="#{msgs.cfg.skin.richSelector}" />

但是,与其像这样设置系统属性,不如像 Ryan Lubke 在他的博客中提到的那样通过 JNDI 配置 ProjectStage,这样您甚至可以使用相同的属性javax.faces.PROJECT_STAGE上下文参数。