Spring Bootプロジェクトにおけるpropertiesファイルの文字化け対策

Aliyunのstart.aliyun.comを使用してSpring Bootプロジェクトを作成する際、application.propertiesファイルが文字化けする問題に遭遇することがあります。これは主に文字エンコーディングの不一致が原因です。以下では、この問題を解決し、propertiesファイルを正しく読み込み・表示できるようにするための手順と方法を詳しく説明します。

1. ファイルエンコーディングをUTF-8に設定する
  1. IDEのエンコーディング設定
  • 開発環境(IntelliJ IDEAやEclipseなど)のファイルエンコーディングをUTF-8に設定してください。
  • IntelliJ IDEAの場合、設定パスは「File -> Settings -> Editor -> File Encodings」で、グローバルエンコーディング、プロジェクトエンコーディング、プロパティファイルエンコーディングをすべてUTF-8に変更します。
  • Eclipseでは、「Window -> Preferences -> General -> Workspace」からテキストファイルのエンコーディングをUTF-8に設定します。
  1. propertiesファイルのエンコーディング確認
  • application.propertiesファイルを開き、そのファイルがUTF-8エンコードであることを確認してください。
  • メモ帳やNotepad++などのエディタを使って、ファイルのエンコーディングを確認・変更できます。
2. Mavenでのエンコーディング設定

Mavenプロジェクトにおいて、pom.xmlに適切なエンコーディング設定を追加してください。

  1. リソースのエンコーディング設定を追加
<project>
    ...
    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                </includes>
                <filtering>false</filtering>
                <encoding>UTF-8</encoding>
            </resource>
        </resources>
    </build>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    </properties>
    ...
</project>
3. Spring Bootの設定

Spring Bootアプリケーションが起動時にUTF-8を使用するように設定します。

  1. application.propertiesにエンコーディングを追加
spring.messages.encoding=UTF-8
  1. 起動クラスでデフォルトエンコーディングを設定
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        System.setProperty("file.encoding", "UTF-8");
        SpringApplication.run(Application.class, args);
    }
}
4. Web環境のエンコーディング設定

Web環境におけるエンコーディングも適切に設定する必要があります。

  1. 内蔵サーバーのエンコーディング設定
server.tomcat.uri-encoding=UTF-8
server.servlet.encoding.charset=UTF-8
server.servlet.encoding.enabled=true
server.servlet.encoding.force=true
  1. Spring MVCのメッセージコンバーター設定
@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        StringHttpMessageConverter converter = new StringHttpMessageConverter(StandardCharsets.UTF_8);
        converter.setWriteAcceptCharset(false);
        converters.add(converter);
    }
}

タグ: Spring Boot propertiesファイル UTF-8 文字化け Maven

9月5日 10:24 投稿