【Spring Boot】Day02

一、读取yml配置文件的值

单引号和双引号的区别:

  • 单引号不会保存其功能;
  • 双引号会保存功能。
name: "123\n123"
输出: 
123
123
name: '123\n123'
输出:123\n123

二、读取properties配置文件的值

在这里插入图片描述

代码

配置文件

server.port=8080

person.name=张三
person.age=18
person.birth=2020/01/01
person.b=true
person.maps.k1=v1
person.maps.k2=v2
person.lists=a,b,c
person.dog.name=xiaogou
person.dog.age=10

person 类中的修改:

需要:

  1. 类前面加入 @Component
  2. 在每个变量上面加入:@Value(“${person.name}”),这要跟配置文件保持一致
package com.zy.springboot.bean;

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

import java.util.Date;
import java.util.List;
import java.util.Map;
/***
 *
 * 读取配置文件中的数据,映射到此类的同名属性
 * @ConfigurationProperties
 *  prefix = "person": 读取person节点的数据
 *  @Component:让spring容器管理此类
 *
 *@Value("${person.name}") 参数名字必须和配置文件中的一样,即可跳转
 */
@Component
//@ConfigurationProperties(prefix = "person")
public class Person {
    @Value("${person.name}")
    private String name;
    @Value("${person.age}")
    private Integer age;
    @Value("${person.birth}")
    private Date birth;
    @Value("${person.b}")
    private Boolean b;
    private Map<String,String> maps;
    private List<String> lists;
    private Dog dog;

    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 Date getBirth() {
        return birth;
    }

    public void setBirth(Date birth) {
        this.birth = birth;
    }

    public Boolean getB() {
        return b;
    }

    public void setB(Boolean b) {
        this.b = b;
    }

    public Map<String, String> getMaps() {
        return maps;
    }

    public void setMaps(Map<String, String> maps) {
        this.maps = maps;
    }

    public List<String> getLists() {
        return lists;
    }

    public void setLists(List<String> lists) {
        this.lists = lists;
    }

    public Dog getDog() {
        return dog;
    }

    public void setDog(Dog dog) {
        this.dog = dog;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", birth=" + birth +
                ", b=" + b +
                ", maps=" + maps +
                ", lists=" + lists +
                ", dog=" + dog +
                '}';
    }
}

三、解决乱码

在显示中文中,
解决中文乱码,一定要在代码之前就配置好这个环境:
在这里插入图片描述
展示
在这里插入图片描述

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值