获取yml对象
写yml
server:
port: 80
user:
name: "小明"
number: 100
age: 18
写pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 支持 @ConfigurationProperties 注解 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
<scope>provided</scope>
</dependency>
写bean类
package top.chenyp.utils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import top.chenyp.bean.User;
@Component
@ConfigurationProperties(prefix = "user1")
public class TestUtils {
@Value("${user1.name}")
private String name;
@Value("${user1.number}")
private Integer number;
@Value("${user1.age}")
private Integer age;
public User test01(){
User user = new User();
user.setName(name);
user.setAge(age);
user.setNumber(number);
return user;
}
}
换个复杂的数据
novellist:
list:
- name: 笑傲江湖
type: 武侠
master: 令狐冲
author: 金庸
description: 小说以通过叙述华山派大弟子令狐冲的经历,反映了武林各派争霸夺权的历程。
- name: 诛仙
type: 仙侠
master: 张小凡
author: 萧鼎
description: 该小说以“天地不仁,以万物为刍狗”为主题,讲述了青云山下的普通少年张小凡的成长经历以及与两位奇女子凄美的爱情故事,整部小说构思巧妙、气势恢宏,开启了一个独具魅力的东方仙侠传奇架空世界,情节跌宕起伏,人物性格鲜明,将爱情、亲情、友情与波澜壮阔的正邪搏斗、命运交战汇集在一起,文笔优美,故事生动。
- name: 英雄志
type: 武侠
master: 观海云远
author: 孙晓
description: 《英雄志》为一虚构中国明朝历史的古典小说,借用明英宗土木堡之变为背景,以复辟为舞台,写尽了英雄们与时代间的相互激荡,造反与政变、背叛与殉道
bean类
package top.chenyp.utils;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;
@Data
@Component
@ConfigurationProperties(prefix = "novellist")
public class NovelList {
private List<Map<String, String>> list;
public List<Map<String, String>> test01(){
System.out.println(list);
return list;
}
}
测试
package top.chenyp.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.chenyp.bean.User;
import top.chenyp.utils.NovelList;
import top.chenyp.utils.TestUtils;
import java.util.List;
import java.util.Map;
@RestController
public class TestController {
@Autowired
TestUtils testUtils;
@Autowired
NovelList novelList;
@RequestMapping("/test")
public List<Map<String, String>> test01(){
return novelList.test01();
}
}