Spring 最佳实践~1、PropertyPlaceholderConfigurer 乱码解决方案

PropertyPlaceholderConfigurer 乱码解决方案

一、问题描述

使用 PropertyPlaceholderConfigurer 读取配置文件时,发现对于中文的处理会出现乱码现象。

二、示例

app-context-processor.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">


    <bean id="testBean" class="com.luo.spring.guides.post.processor.PostProcessorTestBean">
        <property name="name">
            <value>${bean.name}</value>
        </property>
    </bean>

    <bean id="testBeanHandler" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>postprocessor/bean.properties</value>
            </list>
        </property>
    </bean>
</beans>

bean.properties

bean.name=我是小小罗

PostProcessorTestBean.java

package com.luo.spring.guides.post.processor;

import lombok.Data;

/**
 * @author : archer
 * @date : Created in 2023/1/3 11:36
 * @description :
 */
@Data
public class PostProcessorTestBean {
    private String name;
}

测试

package com.luo.spring.guides.post.processor;

import org.springframework.context.support.GenericXmlApplicationContext;

import java.util.Locale;

/**
 * @author : archer
 * @date : Created in 2023/1/3 11:38
 * @description :
 */
public class Main {
    public static void main(String... args) {
        GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
        ctx.load("classpath:postprocessor/app-context-processor.xml");
        ctx.refresh();

        PostProcessorTestBean testBean = ctx.getBean("testBean", PostProcessorTestBean.class);
        System.out.println(testBean.getName());
        ctx.close();
    }
}

输出

我是小小罗

三、解决思路

1、寻找编码属性

  • 通过查看 PropertyPlaceholderConfigurer 的继承关系,发现其父类 PropertiesLoaderSupport 中存在 fileEncoding 属性

2、查看加载配置的方法

/**
	 * Load properties into the given instance.
	 * @param props the Properties instance to load into
	 * @throws IOException in case of I/O errors
	 * @see #setLocations
	 */
protected void loadProperties(Properties props) throws IOException {
		if (this.locations != null) {
			for (Resource location : this.locations) {
				if (logger.isTraceEnabled()) {
					logger.trace("Loading properties file from " + location);
				}
				try {
					PropertiesLoaderUtils.fillProperties(
							props, new EncodedResource(location, this.fileEncoding), this.propertiesPersister);
				}
				catch (FileNotFoundException | UnknownHostException | SocketException ex) {
					if (this.ignoreResourceNotFound) {
						if (logger.isDebugEnabled()) {
							logger.debug("Properties resource not found: " + ex.getMessage());
						}
					}
					else {
						throw ex;
					}
				}
			}
		}
	}

3、使用编码属性

  • 在配置中加上编码属性 fileEncoding,指定为 utf-8

四、解决方案示例

PropertyPlaceholderConfigurer 加上 fileEncoding 属性配置

<property name="fileEncoding">
    <value>utf-8</value>
</property>

app-context-processor.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">


    <bean id="testBean" class="com.luo.spring.guides.post.processor.PostProcessorTestBean">
        <property name="name">
            <value>${bean.name}</value>
        </property>
    </bean>

    <bean id="testBeanHandler" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>postprocessor/bean.properties</value>
            </list>
        </property>
        <property name="fileEncoding">
            <value>utf-8</value>
        </property>
    </bean>
</beans>

输出

我是小小罗

五、小结

  • 解决思路才是精髓。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值