能否在messages.properties中引用其他属性?若可以该如何实现?
问题原因
${} 形式的属性引用是 Spring Boot 核心配置文件(application.properties/yml)的专属功能,由 Spring 环境的属性源处理器实现解析。而 messages.properties 作为国际化资源文件,默认由 JDK 原生 ResourceBundle 加载,本身不支持同文件内的属性占位符解析,因此在 Thymeleaf 中直接输出未解析的原始字符串。
可行解决方案
方案1:自定义 MessageSource 支持属性引用
通过自定义 Spring 的 ReloadableResourceBundleMessageSource 启用占位符解析,实现同文件属性互引:
- 首先在
application.properties中添加配置,将国际化资源文件加入 Spring 环境的属性源:
spring.config.import=classpath:messages.properties
- 新增配置类替换默认的 MessageSource 实现:
import org.springframework.context.MessageSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.support.ReloadableResourceBundleMessageSource; import org.springframework.core.env.Environment; @Configuration public class MessageSourceConfig { private final Environment env; public MessageSourceConfig(Environment env) { this.env = env; } @Bean public MessageSource messageSource() { ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); // 若你的国际化文件有自定义路径或前缀,修改此处 basename 配置 messageSource.setBasename("classpath:messages"); messageSource.setDefaultEncoding("UTF-8"); // 绑定 Spring 环境,自动解析 ${} 占位符 messageSource.setEnvironment(env); return messageSource; } }
配置完成后,你原来写的 ${referenced.text.property} 引用形式就可以正常解析生效。
方案2:用国际化参数占位实现复用(无需改配置)
如果仅小范围复用通用文本,可以直接使用 Thymeleaf 国际化的参数传递能力,不需要修改底层配置:
- 修改
messages.properties配置,用{}占位符预留参数位:
referenced.text.property=Some text new.text.property={0}
- 在 Thymeleaf 模板中调用时传入要复用的属性值:
<p th:text="#{new.text.property(#{referenced.text.property})}"></p>
内容的提问来源于stack exchange,提问作者ArtflPhenix
相关产品推荐
相关产品推荐

