在Spring Boot应用程序中,可以使用YAML文件来配置应用程序的属性。下面是一个示例yaml配置文件:
lesson: SpringBoot
server:
port: 80
enterprise:
name: itcast
age: 16
tel: 400661312
subject:
- Java
- pp
- aasdsda
将上述内容存储在application.yml或application.yaml文件中,可以让Spring按以下方式读取:
方法一:
使用@Value读取单个数据,属性名引用方式:${一级属性名.二级属性名......}
方法二:
封装全部数据到Environment对象
package com.itzhuo.controller;
import com.itheima.domain.Enterprise;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/books")
public class BookController {
//方法一
@Value("${lesson}")
private String lesson;
@Value("${server.port}")
private Integer port;
@Value("${enterprise.subject[0]}")
private String subject_00;
//方法二
@Autowired
private Environment environment;
@GetMapping("/{id}")
public String getById(@PathVariable Integer id){
System.out.println(lesson);
System.out.println(port);
System.out.println(subject_00);
System.out.println("----------------------");
System.out.println(environment.getProperty("lesson"));
System.out.println(environment.getProperty("server.port"));
System.out.println(environment.getProperty("enterprise.subject[1]"));
return "hello,spring boot";
}
}
结果:
方法三:
自定义对象封装指定数据