【发布时间】:2018-03-21 10:39:31
【问题描述】:
我一直在尝试使用 MessageSource 创建一个演示 spring boot 应用程序,但我无法弄清楚问题所在。我尝试了几种方法:
- MessageSourceAutoConfiguration
- 在 @configuration 文件中创建我自己的 bean 并自动装配它
下面是MessageSourceAutoConfiguration方式:
我正在使用 spring-boot-starter-parent 1.5.7.RELEASE。
我的文件夹结构:
DemoApplication.java
@SpringBootApplication
public class DemoApplication
{
public static void main(String[] args)
{
SpringApplication.run(DemoApplication.class, args);
}
}
DemoController.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"));
}
}
Application.yml
spring:
messages:
basename: messages
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 Boot MessageSourceAutoConfiguration
【问题讨论】:
-
小细节,您的消息文件中不应有空格,在“=”和已翻译的消息之间。
-
你把你的
messages.properties放在哪里了。您也可以删除spring.messages.basename属性,因为这是默认值。
标签: java spring-boot