【问题标题】:Spring util:properties - can you change the encoding to UTF-8?Spring util:properties - 你可以将编码更改为 UTF-8 吗?
【发布时间】:2012-01-29 13:00:56
【问题描述】:

我正在将一些属性文件从 iso-8859-1 转换为 utf-8。我为大多数资源文件实现了一个 resource.control,以便它可以读取为 utf-8 编码。

我遇到了一个在 spring 中使用 util:properties 标签定义的属性文件。

我想知道是否有办法指定默认编码为 utf-8?我确实看到了使用 ReloadableResourceBundleMessageSource 将其定义为 bean 的可能性,但是这将需要一个大的重构过程,因为 bean 中的逻辑期望这是一个映射。

使用 spring 3.0.5 定义

<util:properties id="fooProperties" location="file:${AXE_APPCONFIG}/foo.properties"/>

我知道根据定义,java 属性文件是 iso-8859-1 编码的,但是我认为 spring 可能已经想出了一种方法来更改它的编码(如 Resource.Control)

【问题讨论】:

    标签: spring utf-8 properties


    【解决方案1】:

    我发现这是不可能的。 Spring 将始终(从 v3.0.5 开始)使用属性文件的默认编码,即 ISO-8859-1。

    另一种方法是使用属性对象,然后将其转换为地图。

    Properties propsToLoad = new Properties();
    InputStream stream = new FileInputStream("filename.properties");
    propsToLoad.load(new InputStreamReader(stream,"UTF-8));
    

    然后转换为地图

    Map<String,String> mapYouWant = new HashMap<String,String>((Map) propsToLoad);
    

    【讨论】:

      【解决方案2】:

      我最近使用 PropertiesFactoryBean 解决了同样的问题。它是PropertiesLoaderSupport 的子类,它有一个公共的setter 方法供您指定属性文件的编码。

      <beans:bean id="nameOfYourPropsVar" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
          <beans:property name="location" value="classpath:${yourPropFileName}"/>
          <beans:property name="fileEncoding" value="UTF-8"/>
      </beans:bean>
      

      请注意,根据the api doc,它仅适用于经典属性文件,不适用于 XML 文件。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-10-25
        • 2020-12-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-21
        相关资源
        最近更新 更多