【问题标题】:How to refer to a Java .properties file from .xml configuration file (JSF)? [duplicate]如何从 .xml 配置文件 (JSF) 中引用 Java .properties 文件? [复制]
【发布时间】:2015-06-03 02:43:58
【问题描述】:

是否有一种简单的方法可以在 JSF 配置 .xml 文件(例如 faces-config.xml、web.xml 或 applicationContext.xml)中指定我想从外部 .xml 检索配置的某些值。属性文件?这是可以使用 JNDI 或类似方法完成的吗?

例如:

<something>
#{brilliant-code-that-retrieves-values-from-.properties-file}
</something>

提前致谢。

【问题讨论】:

    标签: java xml spring jsf jsf-2


    【解决方案1】:

    是的,有;在 JSF 中,它是使用资源包完成的。

    原版实现

    1. 从您的花园品种开始.properties 文件

      currency.symbol = "$"
      currency.name = "dollar"
      
    2. 在你的 faces.config.xml 文件中定义一个资源包

      <resource-bundle>
          <base-name>com.you.resources.info</base-name>
          <var>paymentInfo</var>
      </resource-bundle> 
      
    3. 请参阅 faces-config.xml 中的资源包(由上下文作为托管对象处理)。请记住 faces-config.xml 文件也处理 EL;出于所有意图和目的,您放置在其中的任何 EL 都会像在视图中一样被扫描:

       <managed-bean>
           <managed-bean-name>YourManagedBean</managed-bean-name>
           <managed-bean-class>
               com.you.app.BeanClass
           </managed-bean-class>
           <managed-bean-scope>session</managed-bean-scope>
           <managed-property>
               <property-name>currencyName</property-name>
               <value>#{paymentInfo['currency.name']}</value>
          </managed-property>
          </managed-bean-name>
       </managed-bean>
      

    加载在 spring 上下文中配置的属性文件

    Spring 使用 util 命名空间 (xmlns:util="http://www.springframework.org/schema/util") 提供开箱即用的属性文件加载。使用相同的配置文件:

    1. 在你的 applicationContext.xml 中定义一个配置器

       <util:properties id="paymentInfo" location="classpath:com/you/resources/info/payment-info.properties" />
      
    2. 您可以在 faces-config.xml 或 applicationContext.xml 中使用 bean #{paymentInfo},就像在上面的 #3 中一样

    【讨论】:

    • OP 询问如何在配置 XML 文件中访问它,而不是如何在 JSF 视图中访问它。
    • 啊,现在我看到了@BalusC
    【解决方案2】:

    对于 web.xml:

    只需在其中放一个上下文参数

    <context-param>
        <param-name>something</param-name>
        <param-value>#{brilliant-code-that-retrieves-values-from-.properties-file}</param-value>
    </context-param>
    

    在代码中以任何您喜欢的方式检索该参数,例如通过 bean 中的 CDI,然后评估检索到的 String 作为表达式。例如。与

    @Inject   
    private ServletContext context;
    
    public MySomething getMySomething() {
    
        final String mySomethingString = context.getInitParameter("something");
        final ELContext elCtx = FacesContext.getCurrentInstance().getELContext();
        (MySomething) mySomething = (MySomething) child.getValueExpression().getValue(elCtx);    
        return mySomething;
    }
    

    【讨论】:

    • 谢谢,但我将如何检索 .properties 文件值并在 xml 配置文件中使用它?我认为您的示例检索上下文参数值并在 .java 代码中使用它。
    猜你喜欢
    • 2016-09-05
    • 2011-02-19
    • 2017-09-16
    • 2019-12-16
    • 2012-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-20
    相关资源
    最近更新 更多