【问题标题】:spring boot setting up message.properties and errors.properties file in the project structure and reading file to codespring boot 在项目结构中设置message.properties和errors.properties文件并读取文件到代码
【发布时间】:2015-06-03 18:25:59
【问题描述】:

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

【问题讨论】:

    标签: spring spring-mvc spring-boot


    【解决方案1】:

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

    errors.key1=value1
    errors.key2=value2
    
    sql.key1=value1
    ....
    

    然后你可以使用@ConfigurationProperties 注解将这些配置映射到封装每种类型的类。

    @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

    【讨论】:

    • 感谢您的回复。如果我必须制作另一个文件是errors.properties 和sql.properties,我想再问一件事。我应该把这个文件放在哪里以便它可以读取。有没有可能?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-25
    • 1970-01-01
    • 1970-01-01
    • 2021-11-27
    • 2017-06-18
    • 2016-04-29
    • 1970-01-01
    相关资源
    最近更新 更多