我一直在尝试使用 MessageSource 创建一个演示 spring boot 应用程序,但我无法弄清楚问题是什么。我尝试了几种方法:
- 消息源自动配置
- 在 @configuration 文件中创建我自己的 bean 并自动装配它
下面是 MessageSourceAutoConfiguration 方式:
我正在使用 spring-boot-starter-parent 1.5.7.RELEASE 。
我的文件夹结构:
演示应用程序.java
@SpringBootApplication
public class DemoApplication
{
public static void main(String[] args)
{
SpringApplication.run(DemoApplication.class, args);
}
}
演示控制器.java
@RestController
public class DemoController implements MessageSourceAware
{
private MessageSource messageSource;
@Override
public void setMessageSource(MessageSource messageSource)
{
this.messageSource = messageSource;
}
@RequestMapping("demo")
public String getLocalisedText()
{
return messageSource.getMessage("test", new Object[0], new Locale("el"));
}
}
应用.yml
spring:
messages:
basename: messages
消息.properties
test=This is a demo app!
messages_el.properties
test=This is a greek demo app!
pom.xml
<groupId>com.example.i18n.demo</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.7.RELEASE</version>
<relativePath />
<!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-
8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
启动服务器时,我可以看到 AutoConfiguration 有效,但找不到 bean:
MessageSourceAutoConfiguration matched:
- ResourceBundle found bundle URL [file:/C:/Users/{user}/Downloads/demo/demo/target/classes/messages.properties] (MessageSourceAutoConfiguration.ResourceBundleCondition)
- @ConditionalOnMissingBean (types: org.springframework.context.MessageSource; SearchStrategy: current) did not find any beans (OnBeanCondition)
我也试图明确声明我自己的 bean,但没有用。
调用端点时出现以下错误:
{
"status": 500,
"error": "Internal Server Error",
"exception": "org.springframework.context.NoSuchMessageException",
"message": "No message found under code 'test' for locale 'el'.",
"path": "/demo"
}
我发现的最接近的 SO 问题是这个(2 岁)关于 spring 中的一个错误,该错误在几个版本前已修复: Spring Boot MessageSourceAutoConfiguration
原文由 nicolas 发布,翻译遵循 CC BY-SA 4.0 许可协议
问题是我的 Eclipse 编码配置,我还没有设法修复它。
在调试了 Spring 的代码(
ReloadableResourceBundleMessageSource.java
)之后,我可以看到我的key=value
属性已加载,但每个字符前有 3 个空格字符(例如t e s t = T h i s i s a d e m o a p p !
)。在另一台 PC 上,相同的演示应用程序运行良好。