ZetCode

Spring MessageSource

最后修改于 2023 年 10 月 18 日

Spring MessageSource 教程展示了如何在 Spring 应用程序中使用 MessageSource 来翻译消息。

Spring 是一个流行的 Java 应用程序框架,用于创建企业级应用程序。

Spring MessageSource

MessageSource 用于解析消息,支持消息的参数化和国际化。Spring 包含两个内置的 MessageSource 实现:ResourceBundleMessageSourceReloadableResourceBundleMessageSource。后者能够在不重启虚拟机的情况下重新加载消息定义。

Spring MessageSource 示例

下面的应用程序包含英语和德语的消息。它使用了内置的 ResourceBundleMessageSource

pom.xml
src
├───main
│   ├───java
│   │   └───com
│   │       └───zetcode
│   │           │   Application.java
│   │           └───config
│   │                   AppConfig.java
│   └───resources
│       │   logback.xml
│       └───messages
│               label.properties
│               label_de.properties
└───test
    └───java

这是项目结构。

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
            http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.zetcode</groupId>
    <artifactId>messagesource</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <spring-version>5.3.23</spring-version>

    </properties>

    <dependencies>

        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.4.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring-version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring-version}</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>3.1.0</version>
                <configuration>
                    <mainClass>com.zetcode.Application</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

pom.xml 文件中,我们有基本的 Spring 依赖 spring-corespring-context 和日志 logback-classic 依赖。

exec-maven-plugin 用于从 Maven 命令行执行 Spring 应用程序。

resources/logback.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <logger name="org.springframework" level="ERROR"/>
    <logger name="com.zetcode" level="INFO"/>

    <appender name="consoleAppender" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <Pattern>%d{HH:mm:ss.SSS} %blue(%-5level) %magenta(%logger{36}) - %msg %n
            </Pattern>
        </encoder>
    </appender>

    <root>
        <level value="INFO" />
        <appender-ref ref="consoleAppender" />
    </root>
</configuration>

logback.xml 是 Logback 日志库的配置文件。

resources/messages/labels.properties
l1=Earth
l2=Hello {0}, how are you?

这是英语消息。第二个属性接收一个参数。

resources/messages/labels_de.properties
l1=Erde
l2=Hallo {0}, wie geht's?

这是德语消息。

com/zetcode/config/AppConfig.java
package com.zetcode.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;

@Configuration
public class AppConfig {

    @Bean
    public ResourceBundleMessageSource messageSource() {

        var source = new ResourceBundleMessageSource();
        source.setBasenames("messages/label");
        source.setUseCodeAsDefaultMessage(true);

        return source;
    }
}

AppConfig 配置了 ResourceBundleMessageSourcesetBasenames 指定了消息定义的查找位置。

com/zetcode/Application.java
package com.zetcode;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;

import java.util.Locale;

@ComponentScan(basePackages = "com.zetcode")
public class Application {

    private static final Logger logger = LoggerFactory.getLogger(Application.class);

    @Autowired
    private MessageSource messageSource;

    public static void main(String[] args) {

        var ctx = new AnnotationConfigApplicationContext(Application.class);

        var app = ctx.getBean(Application.class);
        app.run();

        ctx.close();
    }

    public void run() {

        logger.info("Translated messages:");
        logger.info("{}", messageSource.getMessage("l1",
                null, Locale.GERMAN));
        logger.info("{}", messageSource.getMessage("l1",
                null, Locale.ENGLISH));

        logger.info("Translated parameterized messages:");
        logger.info("{}", messageSource.getMessage("l2",
                new Object[] {"Paul Smith"}, Locale.GERMAN));
        logger.info("{}", messageSource.getMessage("l2",
                new Object[] {"Paul Smith"}, Locale.ENGLISH));
    }
}

该应用程序将普通消息和参数化消息打印到控制台。

@Autowired
private MessageSource messageSource;

我们注入了在 AppConfig 中生成的 MessageSource

logger.info("{}", messageSource.getMessage("l1",
    null, Locale.GERMAN));

getMessage 的第一个参数是属性名。第二个参数是 null,因为该消息不带参数。第三个参数是 locale。

logger.info("{}", messageSource.getMessage("l2",
    new Object[] {"Paul Smith"}, Locale.GERMAN));

这里我们也为消息提供了一个参数。

$ mvn -q exec:java
22:08:27.984 INFO  com.zetcode.Application - Translated messages:
22:08:27.984 INFO  com.zetcode.Application - Erde
22:08:27.984 INFO  com.zetcode.Application - Earth
22:08:27.984 INFO  com.zetcode.Application - Translated parameterized messages:
22:08:27.984 INFO  com.zetcode.Application - Hallo Paul Smith, wie gehts?
22:08:27.984 INFO  com.zetcode.Application - Hello Paul Smith, how are you?

我们运行应用程序。

在这篇文章中,我们展示了如何在 Spring 应用程序中使用 ResourceBundleMessageSource

作者

我叫 Jan Bodnar,是一名充满热情的程序员,拥有丰富的编程经验。我从 2007 年开始撰写编程文章,至今已撰写了 1,400 多篇文章和 8 本电子书。我在编程教学方面拥有十多年的经验。

列出 所有 Spring 教程