java国际化配置文件如何使用UTF8

发布于:2024-06-07 ⋅ 阅读:(120) ⋅ 点赞:(0)

1.直接设置SpringMessage的编码

import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;

@AutoConfiguration
public class MessageSourceConfig {
    @Bean
    public MessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename("classpath:i18n/messages");
        messageSource.setDefaultEncoding("UTF-8");
        return messageSource;
    }
}

2.使用XML格式的配置文件

import com.zyym.common.core.i18n.XmlMessageSource;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;

@AutoConfiguration
public class MessageSourceConfig {

    @Bean
    public MessageSource messageSource() {
        return new XmlMessageSource(new String[]{"messages"});
    }
}
import org.springframework.context.support.AbstractMessageSource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.DefaultPropertiesPersister;

import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.Locale;
import java.util.Properties;

public class XmlMessageSource extends AbstractMessageSource {

    private final Properties properties = new Properties();

    public XmlMessageSource(String[] basenames) {
        for (String basename : basenames) {
            loadProperties(basename);
        }
    }

    private void loadProperties(String basename) {
        try {
            Resource resource = new ClassPathResource(basename + ".xml");
            InputStream inputStream = resource.getInputStream();
            DefaultPropertiesPersister persister = new DefaultPropertiesPersister();
            persister.loadFromXml(properties, inputStream);
        } catch (IOException e) {
            throw new RuntimeException("Failed to load properties from XML file: " + basename, e);
        }
    }

    @Override
    protected MessageFormat resolveCode(String code, Locale locale) {
        String msg = properties.getProperty(code);
        if (msg != null) {
            return new MessageFormat(msg, locale);
        }
        return null;
    }

    @Override
    protected String resolveCodeWithoutArguments(String code, Locale locale) {
        return properties.getProperty(code);
    }
}

messages_en_US.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
    <entry key="notice.title">notice.title</entry>
    <entry key="not.script">not.script</entry>
    <entry key="not.null">not.null</entry>
</properties>

网站公告

今日签到

点亮在社区的每一天
去签到