springboot配置文件

springboot配置文件

配置文件的几种后缀

<resource>
	<directory>${basedir}/src/main/resources</directory>
	<excludes>
		<exclude>**/application*.yml</exclude>
		<exclude>**/application*.yaml</exclude>
		<exclude>**/application*.properties</exclude>
	</excludes>
</resource>

对应的语法结构

springboot使用一个全局的配置文件,配置文件名称是固定的

  • application.properties
    语法结构:key=value
  • application.yml/application.yaml
    语法结构: key: 空格 value

配置文件的作用

修改springboot自动配置的默认值,因为springboot在底层都给我们配置好了。

一些基本用法

# 普通的key-value
name: Haley

# 对象
student1:
  name: Haley
  age: 20

# 行内写法
student2: {name: Haley,age: 20}

# 数组
pets1:
  - cat
  - dog
  - pig

pets2: [cat,dog,pig]

给实体类赋值的几种方法

1. 直接赋值

  • 实体类
@Component
@Data
public class Dog {
    @Value("旺财")
    private String name;
    @Value("3")
    private Integer age;
}
  • 测试
@SpringBootTest
class NginxApplicationTests {

    @Autowired
    private Dog dog;

    @Test
    void contextLoads() {
        System.out.println(dog);
    }
    
}
  • 结果
    在这里插入图片描述

2. 通过配置文件赋值

  • 同时给多个变量赋值
person:
  name: Haley
  age: 20
  happy: false
  birth: 2019/11/02
  maps: {k1: v1,k2: v2}
  lists: [code,music,pet]
  dog:
    name: 旺财
    age: 3
@Component
@Data
@ConfigurationProperties(prefix = "person")//使用@ConfigurationProperties
public class Person {
    private String name;
    private Integer age;
    private Boolean happy;
    private Date birth;
    private Map<String,Object> maps;
    private List<Object> lists;
    private  Dog dog;
}
@SpringBootTest
class NginxApplicationTests {

    @Autowired
    private Person person;

    @Test
    void contextLoads() {
        System.out.println(person);//打印person,查看是否赋值成功
    }

}

在这里插入图片描述

  • 给单个变量赋值
@Component
@Data
public class Dog {
    @Value("${name}")
    private String name;
    @Value("${age}")
    private Integer age;
}

配置文件的位置

在这里插入图片描述

优先级:①>④>②>③

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值