资讯专栏INFORMATION COLUMN

SpringBoot学习笔记:Spring Boot配置文件详解

sunny5541 / 2055人阅读

摘要:全局配置文件默认为下的,另外它还可以重命名为格式即对着两种格式均支持。其中每个环境的数据库地址服务器端口等等配置都会不同,如果在为不同环境打包时都要频繁修改配置文件的话,那必将是个非常繁琐且容易发生错误的事。

SpringBoot全局配置文件默认为src/main/resources下的application.properties,另外它还可以重命名为.yml格式(即SpringBoot对着两种格式均支持)。

修改默认配置

如修改SpringBoot内嵌Tomcat的启动端口为9080(.yml格式)

server:
  port: 9080

启动项目即可在控制台启动日志中看到

s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 9080 (http)

这时在浏览器输入localhost:9080即可正常访问
附SpringBoot Common application properties

自定义属性配置

我们也可以在SpringBoot配置文件中自定义属性配置,如

girl:
  name: baby
  age: 18
  cupSize: B

然后通过@Value("${属性名}")注解来加载对应的配置属性

package cn.fulgens.springboot.springbootconfig.web;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @Value("${girl.name}")
    private String girlName;

    @Value("${girl.age}")
    private Integer girlAge;

    @Value("${girl.cupSize}")
    private String girlCupSize;

    @GetMapping("/girl")
    public String girl() {
        return "girlName: " + girlName + " girlAge: " + girlAge + " girlCupSize: " + girlCupSize;
    }

}

启动工程,访问:localhost:9080/girl,浏览器显示:

girlName: baby girlAge: 18 girlCupSize: B

属性注入成功

属性配置间的引用

在SpringBoot全局配置文件中的各个属性之间可以通过直接引用来使用

girl:
  name: baby
  age: 18
  cupSize: B
  desc: ${girl.name} ${girl.age} ${girl.cupSize}

同样可以使用@Value注解将girl.desc属性配置注入到某一属性中,如

@RestController
public class HelloController {

    @Value("${girl.name}")
    private String girlName;

    @Value("${girl.age}")
    private Integer girlAge;

    @Value("${girl.cupSize}")
    private String girlCupSize;

    @Value("${girl.desc}")
    private String girlDesc;

    @GetMapping("/girl")
    public String girl() {
        // return "girlName: " + girlName + " girlAge: " + girlAge + " girlCupSize: " + girlCupSize;
        return girlDesc;
    }

}

再次启动工程,访问:localhost:9080/girl,浏览器显示:

baby 18 B
将属性配置赋给实体类

当我们属性配置很多的时候,使用@Value注解一个一个的注入将会变得很繁琐,这时SpringBoot提供了将属性配置与实体类结合的方式,具体先来看一下SpringBoot中官方的使用如org.springframework.boot.autoconfigure.data.redis.RedisProperties

package org.springframework.boot.autoconfigure.data.redis;

import java.util.List;
import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(
    prefix = "spring.redis"
)
public class RedisProperties {
    private int database = 0;
    private String url;
    private String host = "localhost";
    private String password;
    private int port = 6379;
    private boolean ssl;
    private int timeout;
    private RedisProperties.Pool pool;
    private RedisProperties.Sentinel sentinel;
    private RedisProperties.Cluster cluster;
    
    ...
}

对于上面我们自己关于girl的一些配置,同理我们可以创建一个GirlProperties类,如

package cn.fulgens.springboot.springbootconfig.properties;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@ConfigurationProperties(prefix = "girl")
@Component
public class GirlProperties {

    private String name;

    private Integer age;

    private String cupSize;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getCupSize() {
        return cupSize;
    }

    public void setCupSize(String cupSize) {
        this.cupSize = cupSize;
    }
}

注意这里指定了@ConfigurationProperties注解的prefix,同时以上@Component注解可加可不加
有时可能还需要在pom.xml中加上以下依赖

    
        org.springframework.boot
        spring-boot-configuration-processor
        true
    

那么如何使用呢?我们需要在需要使用的类上加@EnableConfigurationProperties注解,同时使用@Autowired注解注入即可,如

package cn.fulgens.springboot.springbootconfig.web;

import cn.fulgens.springboot.springbootconfig.properties.GirlProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@EnableConfigurationProperties(GirlProperties.class)
public class HelloController {

    @Autowired
    private GirlProperties girlProperties;
    
    @GetMapping("/girl")
    public String girl() {
        return girlProperties.getName() + "--" + girlProperties.getAge() + "--" +girlProperties.getCupSize();
    }

}

再次启动工程,访问:localhost:9080/girl,浏览器显示:

baby--18--B
使用随机值

Spring Boot的属性配置文件中可以通过${random}来产生随机int、long、uuid或者string字符串,来支持属性的随机值。

比如我们给girl随机来个年龄

age: ${random.int}
自定义配置文件

虽然SprinBoot提供了application.properties或application.yml全局配置文件,但有时我们还是需要自定义配置文件,如将上文关于girl的属性配置提取到girl.properties文件中,那么如何让spring读取这个属性配置文件呢?答案是使用@PropertySource(value = "classpath:girl.properties")当然如果这样写需要将girl.properties文件放在类路径下
结合属性配置类的用法如下:

@Configuration
@PropertySource(value = "classpath:girl.properties")
@ConfigurationProperties(prefix = "girl")
public class GirlProperties {

    private String name;

    private Integer age;

    private String cupSize;

    ...
}
多环境配置

开发Spring Boot应用时,通常同一套程序会被应用和安装到几个不同的环境,比如:开发、测试、生产等。其中每个环境的数据库地址、服务器端口等等配置都会不同,如果在为不同环境打包时都要频繁修改配置文件的话,那必将是个非常繁琐且容易发生错误的事。
在Spring Boot中多环境配置文件名需要满足application-{profile}.properties的格式,其中{profile}对应你的环境标识,比如:

application-test.yml:测试环境

application-dev.yml:开发环境

application-prod.yml:生产环境

哪个profile会被激活?在application.yml文件中通过spring.profiles.active属性来设置,其值对应{profile}值
这里在类路径下创建application-dev.yml配置server.port为8080,并在application.yml中配置spring.profiles.active为dev
再次启动工程,访问:localhost:8080/girl即可正常访问

参考自
慕课廖师兄girl案例

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/76382.html

相关文章

  • Java学习路线总结,搬砖工逆袭Java架构师(全网最强)

    摘要:哪吒社区技能树打卡打卡贴函数式接口简介领域优质创作者哪吒公众号作者架构师奋斗者扫描主页左侧二维码,加入群聊,一起学习一起进步欢迎点赞收藏留言前情提要无意间听到领导们的谈话,现在公司的现状是码农太多,但能独立带队的人太少,简而言之,不缺干 ? 哪吒社区Java技能树打卡 【打卡贴 day2...

    Scorpion 评论0 收藏0
  • 写这么多系列博客,怪不得找不到女朋友

    摘要:前提好几周没更新博客了,对不断支持我博客的童鞋们说声抱歉了。熟悉我的人都知道我写博客的时间比较早,而且坚持的时间也比较久,一直到现在也是一直保持着更新状态。 showImg(https://segmentfault.com/img/remote/1460000014076586?w=1920&h=1080); 前提 好几周没更新博客了,对不断支持我博客的童鞋们说声:抱歉了!。自己这段时...

    JerryWangSAP 评论0 收藏0
  • SpringBoot 实战 (二) | 第一个 SpringBoot 工程详解

    摘要:代码如下可以看到中一共有个依赖,其中只有是我手动加入的,用于单元测试。点击项目启动按钮,效果如下好的程序必须配备完善的单元测试。测试结果如下可以看到红圈框住的地方,出现这个绿色标志证明单元测试没问题。 微信公众号:一个优秀的废人如有问题或建议,请后台留言,我会尽力解决你的问题。 前言 哎呦喂,按照以往的惯例今天周六我的安排应该是待在家学学猫叫啥的。但是今年这种日子就可能一去不复返了,没...

    GeekQiaQia 评论0 收藏0
  • SpringBoot 实战 (二) | 第一个 SpringBoot 工程详解

    摘要:代码如下可以看到中一共有个依赖,其中只有是我手动加入的,用于单元测试。点击项目启动按钮,效果如下好的程序必须配备完善的单元测试。测试结果如下可以看到红圈框住的地方,出现这个绿色标志证明单元测试没问题。 微信公众号:一个优秀的废人如有问题或建议,请后台留言,我会尽力解决你的问题。 前言 哎呦喂,按照以往的惯例今天周六我的安排应该是待在家学学猫叫啥的。但是今年这种日子就可能一去不复返了,没...

    yuxue 评论0 收藏0
  • SpringBoot学习笔记:Getting Started构建第一个Spring Boot工程

    摘要:本文参考官方文档部分特定版本如版本官方文档地址注本文基于构建话说在上已经有多颗星了,足见火爆程度简介以下介绍引自创建独立的应用程序直接嵌入,或无需部署文件提供自己的入门来简化你的配置尽可能自动配置提供生产就绪功能,如指标,运行 本文参考 Spring Boot官方文档 Part II. Getting Started部分特定版本如1.5.10.RELEASE版本官方文档地址:https...

    Drummor 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<