• SpringBoot 读取自定义属性文件


    1、在 resources目录下创建 custom.properties 文件,内容如下:

    custom.name=Java
    custom.module=thread

    2、定义配置类(使用@Value注解注入属性值):

    @Component
    // 指定配置文件路径
    @PropertySource("classpath:custom.properties")
    public class CustomConfig {
        @Value("${custom.name}")
        private String name;
        @Value("${custom.module}")
        private String module;
    
        public String getResult() {
            return "name:" + this.name + ",module:" + this.module;
        }
    
    }

    3、定义配置类(使用 get/set 方法):

    @Component
    @ConfigurationProperties(prefix = "custom")
    @PropertySource("classpath:custom.properties")
    @Data      // 引用 lombok注解
    public class CustomConfig {
    
        private String name;
        private String module;
    
        public String getResult() {
            return "name:" + this.name + ",module:" + this.module;
        }
    
    }

    以上两种配置类的定义,使用任一即可。

    4、进行单元测试:

    /**
     * 测试 SpringBoot 读取自定义属性文件
     */
    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class TestCustomConfig {
    
        /**
         * 注入自定义配置类
         */
        @Autowired
        CustomConfig customConfig;
    
        @Test
        public void testCustom() {
            String result = customConfig.getResult();
            System.out.println(result);     // 结果:name:Java,module:thread
            
        }
    
    }
    艺无止境,诚惶诚恐, 感谢开源贡献者的努力!!
  • 相关阅读:
    构建CMDB的一些启发
    一个NB的安全认证机制
    SQLAlchemy
    Tornado基本使用
    Tornado源码探寻(请求到来)
    Tornado源码探寻(准备阶段)
    Tornado源码探寻(开篇)
    我的个人博客网站
    IDEA/AS快捷键收集&习惯
    ubuntu命令收集
  • 原文地址:https://www.cnblogs.com/d0usr/p/12389577.html
Copyright © 2020-2023  润新知