zoukankan      html  css  js  c++  java
  • 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
            
        }
    
    }
    艺无止境,诚惶诚恐, 感谢开源贡献者的努力!!
  • 相关阅读:
    1203 有穷自动机
    [转]HTTP协议详解
    JavaScript中的正则表达式
    [译]JavaScript insertAdjacentHTML
    [译]Autoprefixer:用最可行的方式处理浏览器前缀的CSS后处理器
    [译]JavaScript 错误和处理
    [译]CSS content
    [译]当你在浏览器输入url后发生了什么
    display的小故事
    移动web屏幕适配方案
  • 原文地址:https://www.cnblogs.com/d0usr/p/12389577.html
Copyright © 2011-2022 走看看