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
        
    }

}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM