spring.messages怎么模糊匹配
时间: 2023-09-08 22:11:35 浏览: 60
在 Spring Boot 中,可以通过在 `spring.messages.basename` 属性中使用通配符来实现模糊匹配。例如,可以将 `spring.messages.basename` 属性设置为 `messages_*`,表示加载所有以 `messages_` 开头的资源文件,如 `messages_en.properties`、`messages_zh.properties` 等。
同时,还可以通过在 MessageSource 中配置 `setUseCodeAsDefaultMessage(true)` 来开启模糊匹配。这样,当找不到对应的消息时,就会使用消息代码作为默认消息。例如,在 `messages_en.properties` 中,定义了一个消息 `hello.world=Hello, World!`,在 `messages_zh.properties` 中,没有定义这个消息,但是定义了一个消息 `hello=你好`。当我们使用 `Locale.ENGLISH` 时,在 `messages_zh.properties` 中就找不到 `hello.world` 对应的消息,此时会使用 `hello.world` 作为默认消息。代码如下:
```java
@Autowired
private MessageSource messageSource;
public String getMessage(String code, Object... args) {
return messageSource.getMessage(code, args, code, LocaleContextHolder.getLocale());
}
```
在上面的代码中,当找不到对应的消息时,使用 `code` 作为默认消息。
需要注意的是,使用模糊匹配时,要确保所有的资源文件都遵循相同的命名规则,否则会出现加载不到资源文件的情况。