关键词搜索

源码搜索 ×
×

spring boot里的配置文件(*.properties)

发布2019-09-05浏览551次

详情内容

spring boot的出现,据说是为了简化spring各种繁琐的XML配置,推崇“约定重于配置”的思想。这果然不是盖的。

就拿spring boot里的配置文件(*.properties)来说吧。

1、系统会把所有的 *.properties 文件当作配置文件对待

一视同仁。配置项不一定要写在application.properties或application.yml里(据说application.properties优先级高于application.yml),比如我在同一目录下建立一个web.properties,里面的配置项同样可以读取,而无需做特殊的声明。
在这里插入图片描述
读取代码:

@Configuration
@PropertySource(value = "classpath:webconfig.properties",encoding = "UTF-8")//这一句不写也可以
@ConfigurationProperties("web")
public class WebConfig {
    private String pubzy;//公用静态资源库
    public String getPubzy() {
        return pubzy;
    }
    public void setPubzy(String pubzy) {
        this.pubzy = pubzy;
    }
    ……
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

2、驼峰命名规则

不管配置文件里的各种配置项怎么命名,驼峰也好,下划线分隔也好,减号连接也好,都能识别,真令人惊讶。

比如配置文件里某配置项以下三种写法(后两个注释了),系统都能识别,能跟代码里的属性绑定。

配置文件web.properties:

cas.server-url-prefix=http://192.168.0.22:9080/cas248
#cas.server_url_prefix=http://192.168.0.22:9080/cas248
#cas.serverUrlPrefix=http://192.168.0.22:9080/cas248
  • 1
  • 2
  • 3

代码:

@Configuration
@PropertySource(value = "classpath:webconfig.properties",encoding = "UTF-8")
@ConfigurationProperties("cas")
public class CasConfig {

    private String serverUrlPrefix;//可以准确无误地指向上述三种配置项

    public String getServerUrlPrefix() {
        return serverUrlPrefix;
    }

    public void setServerUrlPrefix(String serverUrlPrefix) {
        this.serverUrlPrefix = serverUrlPrefix;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

相关技术文章

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载