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

来源:互联网 发布:同步英语听力软件推荐 编辑:程序博客网 时间:2024/05/22 08:56

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

application.test1=aaaapplication.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=aaatest2=bbb

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

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

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

jdbc.test1=ccccjdbc.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容器

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

阅读全文
0 0
原创粉丝点击