YAML配置和应用

SpringBoot可以使用两种配置文件,一种是application.properties;一种是application.yml。

application.properties 语法: key=value
application.yml 语法:key:(空格)value
配置文件的作用:修改SpringBoot自动配置的默认值,因为SpringBoot在底层都给我们配置好了。

YAML和XML

yaml配置:

server:
	prot: 8080

xml配置:

<server>
	<port>8081<port>
</server>

显然YAML更简洁一些。

YAML和Properties

YAML:

#对空格要求很高
#普通的key-value
name: SpringBoot

#对象
student:
    name: xiaoming
    age: 3

#数组
array:[cat,dog,pig]

Properties:

#只能存键值对
name=小明

给对象赋值

方式一:使用@Value注解

package com.example.demo.pojo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

//将该类添加到Spring组件中
@Component
public class Person {
    @Value("韩信")
    private String name;
    @Value("18")
    private int age;

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

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

    @Override
    public String toString() {
        return "person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

测试代码:

package com.example.demo;

import com.example.demo.pojo.Person;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class DemoApplicationTests {

    @Autowired
    Person p ;
    @Test
    void contextLoads() {
        System.out.println(p);
    }

}

在这里插入图片描述

方式二:YAML配置需要@ConfigurationProperties注解
@ConfigurationProperties注解作用:将配置文件中的每一个属性的值,映射到这个组件中;告诉SpringBoot将本类中的所有属性和配置文件相关的配置进行绑定。
YAML文件配置:

person:
    name: 李白
    age: 20
package com.example.demo.pojo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

//将该类添加到Spring组件中
@Component
@ConfigurationProperties(prefix = "person")  //该注解代表是一个配置
public class Person {
    private String name;
    private int age;

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

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

    @Override
    public String toString() {
        return "person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

测试部分同上。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值