java SpringBoot(五)yml配置文件使用

SpringBoot的配置文件默认是application.properties

这次记录一下application.yml的用法(优先级好像是properties,貌似是先加载的为主,具体建议百度,但是两个文件都会兼容并配置)

首先创建两个测试类

Person代码

package com.example.demo.bean;

import lombok.Data;
import lombok.ToString;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Data
@ToString
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
    private String userName;
    private Boolean boss;
    private Date birth;
    private Integer age;
    private Pet pet;
    private String[] interests;
    private List<String> animal;
    private Map<String, Object> score;
    private Set<Double> salarys;
    private Map<String, List<Pet>> allPets;
}

Pet代码

package com.example.demo.bean;

import lombok.Data;
import lombok.ToString;

@Data
@ToString
public class Pet {
    private String name;
    private Double weight;
}

在resources下边新建application.yml文件,编写

person:
  userName: zhangsan
  boss: true
  birth: 2019/12/9
  age: 18
  #interests: [篮球,足球]
  interests:
    - 篮球
    - 足球
    - 18
  animal: [阿猫, 阿狗]
  score: {english: 80, math: 90}
  salarys:
    - 9999
    - 9998
  pet:
    name: 阿狗
    weight: 99.99
  allPets:
    sick:
      - {name: 阿狗, weight: 99.99}
      - name: 阿猫
        weight: 88.88
      - name: 啊虫
        weight: 77.77
    health:
      - {name: 阿花, weight: 99.99}
      - {name: 阿狸, weight: 99.99}




测试并使用,在controller中编写

package com.example.demo.controller;

import com.example.demo.bean.Person;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j //lombok日志功能
@RestController
public class MyController {
    @RequestMapping("/index")
    public String hand1(){
        log.info("收到请求");
        return "hello";
    }

    @Autowired
    Person person; //使用person组件

    @RequestMapping("/person")
    public Person person(){

        return person;
    }
}


然后运行项目,访问person

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值