You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

禁用Spring Data REST回退到系统区域设置的行为

我完全理解你在Spring Boot 2.0.1项目里遇到的这个痛点——想禁用REST消息自动回退到系统区域设置的行为,虽然@wilkinsona给了提示,但实际动手时确实会遇到不少细节问题。下面给你一套完整的可落地方案:

实现步骤与代码示例

1. 自定义RepositoryRestMvcConfiguration配置类

通过继承RepositoryRestMvcConfiguration,我们可以覆盖默认的消息源配置,关闭系统区域设置回退行为。同时保留Spring Boot自动配置的RepositoryRestProperties,确保原有配置的兼容性。

import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration;
import org.springframework.boot.autoconfigure.data.rest.RepositoryRestProperties;
import org.springframework.context.annotation.EnableConfigurationProperties;
import java.time.format.DateTimeFormatter;

@Configuration
@EnableConfigurationProperties(RepositoryRestProperties.class)
public class CustomRepositoryRestMvcConfiguration extends RepositoryRestMvcConfiguration {

    public static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    private final RepositoryRestProperties repositoryRestProperties;

    // 通过构造函数注入RepositoryRestProperties,复用自动配置的属性
    public CustomRepositoryRestMvcConfiguration(RepositoryRestProperties repositoryRestProperties) {
        this.repositoryRestProperties = repositoryRestProperties;
    }

    @Override
    protected void configureRepositoryRestConfiguration(org.springframework.data.rest.core.config.RepositoryRestConfiguration config) {
        super.configureRepositoryRestConfiguration(config);
        // 这里可以添加你的其他自定义配置,比如暴露实体ID字段
        // config.exposeIdsFor(YourEntity.class);
    }

    @Override
    public ReloadableResourceBundleMessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource = super.messageSource();
        // 核心配置:禁用消息回退到系统区域设置
        messageSource.setFallbackToSystemLocale(false);
        // 可选:如果需要自定义消息文件路径,可添加如下配置
        // messageSource.setBasenames("classpath:custom-rest-messages");
        return messageSource;
    }
}

2. 关键配置说明

  • 禁用回退核心:调用messageSource.setFallbackToSystemLocale(false)后,当找不到对应区域的rest-messages_{locale}.properties文件时,不会自动 fallback 到系统默认区域的消息文件,而是直接表现为缺失消息的状态(比如返回默认占位符或抛出对应异常)。
  • 保留自动配置兼容性:注入RepositoryRestProperties确保你的自定义配置不会覆盖Spring Boot自动配置的REST属性(比如base-path、分页设置等)。
  • 自定义消息文件(可选):如果需要替换默认的rest-messages文件,通过setBasenames指定你的自定义文件路径即可。

3. 验证配置

启动项目后,你可以通过设置不同的Accept-Language请求头来测试:

  • 当请求一个不存在对应区域的消息时,系统不会再回退到系统区域设置的消息,符合你预期的自定义行为。

内容的提问来源于stack exchange,提问作者drenda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:35:03