spring boot默认配置文件application.properties的属性读取

本文介绍了Spring Boot中配置文件的多种使用方式,包括通过@ConfigurationProperties注解将配置文件属性映射到Java类,使用@Value注解直接获取配置文件中的值,以及如何加载自定义配置文件。

一.将所有属性封装到一个类中。
1.application.properties中属性为

application.test1=aaa
application.test2=bbb

2.定义一个配置文件的类

@ConfigurationProperties(prefix="application")
public class ApplicationProperties {
    private  String test1;
    private  String test2;
    public String getTest1() {
        return test1;
    }
    public void setTest1(String test1) {
        this.test1 = test1;
    }
    public String getTest2() {
        return test2;
    }
    public void setTest2(String test2) {
        this.test2 = test2;
    } 
}

注意加上此注解,@ConfigurationProperties(prefix=”application”),标明识别的是前缀为application的属性。
3.spring Boot入口类加上@EnableConfigurationProperties注解,使用配置文件。
4.输出结果为

test1=aaa
test2=bbb

二.使用@Value注解方式,个人比较推荐使用,比较灵活方便。
1.properties中定义好属性。
2.这样就可以使用了,不需要其它注解

    @Value("${application.test2}")
    private String msg;

三.使用自定义配置文件
1.jdbc.properties中属性为

jdbc.test1=cccc
jdbc.test2=dddd

2.使用以下注解,标明使用哪个配置文件

@Component
@ConfigurationProperties(prefix="jdbc")
@PropertySource(value={"classpath:jdbc.properties"})
public class ApplicationProperties {
    private  String test1;
    private  String test2;
    public String getTest1() {
        return test1;
    }
    public void setTest1(String test1) {
        this.test1 = test1;
    }
    public String getTest2() {
        return test2;
    }
    public void setTest2(String test2) {
        this.test2 = test2;
    } 
}

3.使用

    @Resource
    private ApplicationProperties applicationProperties;

四.注意事项
1.spring boot默认配置文件为:application.properties,默认已经实例化到spring容器,其它自定义配置文件必须使用@Component实例化到spring容器

写得不好,有错误的地方或表达不全面的地方望提醒,毕竟菜鸟一枚。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值