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
        
    }

}

 

posted @ 2020-03-01 14:06  d0usr  阅读(921)  评论(0编辑  收藏  举报