spring 引导在项目结构中设置 message.properties 和 errors.properties 文件并将文件读入代码

spring boot setting up message.properties and errors.properties file in the project structure and reading file to code

我是 spring 引导新手。我想在项目结构中添加外部属性文件。文件是 errors.properties、messages.propeties 和 sql.properties 文件,其中包含所有 sql 查询。我知道在哪里添加它,即 \demo\src\main\resources\errors.properties 文件。你们中的任何人都可以告诉我如何从这些文件中读取我的 java 代码。

最简单的方法是利用 Spring Boot 已经自动提供的功能。您放入 application.properties(在 \demo\src\main\resources 下)的任何内容都将添加到您的环境中。我只想从这三个文件中获取密钥并在 application.properites

中创建唯一的条目
errors.key1=value1
errors.key2=value2

sql.key1=value1
....

然后您可以使用@ConfigurationProperties 注释将这些配置映射到封装每个类型的class。

@Component
@ConfigurationProperties(prefix="errors")
public class ErrorSettings {

private String key1;
 .....
//getter and setters
}

现在你有了一个 ErrorSettings 类型的 Bean,你可以将它注入到你声明的任何其他 Bean 中,只需调用你想要的配置的 getXXX() 方法。

参考文档:

http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html