我一直在嘗試創建一個帶有MessageSource的演示彈簧啓動應用程序,但我無法弄清楚是什麼問題。我試着在幾個方面:Spring引導應用程序和MessageSource
- MessageSourceAutoConfiguration
- 一個@Configuration文件中創建我自己的豆和自動裝配它
下面是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>
雖然啓動服務器,我可以看到,自動配置的作品,卻找不到一個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)
我想也明確聲明自己豆,但沒」工作。
在調用端點我得到以下錯誤:
{
"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
小細節,你的消息文件中'='和翻譯的消息之間不應該有空格。 – Thibstars
你把你的'messages.properties'放在哪裏?你也可以移除'spring.messages.basename'屬性,因爲它是默認值。 –