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
            
        }
    
    }
    艺无止境,诚惶诚恐, 感谢开源贡献者的努力!!
  • 相关阅读:
    一系列视频教程 收藏
    生成一个4位整数
    spring 实现定时任务
    判断字符串是否包含汉字
    pmd代码安全扫描工具
    IntelliJ IDEA
    李小龙传奇
    checkmarx使用笔记、原理
    pmd 使用笔记
    Mysql的安装(视频+部分视频截图)
  • 原文地址:https://www.cnblogs.com/d0usr/p/12389577.html
Copyright © 2011-2022 走看看