Spring Boot为我们准备了两种配置文件,一种是默认的application.properties,另一种是application.yml。
1、在src/main/resources目录下新建一个名为application.yml的文件,并写入配置内容。
代码:
com:
example:
demo:
name: 回乡偶书
author: 作者:贺知章
content: 少小离家老大回,乡音无改鬓毛衰。儿童相见不相识,笑问客从何处来。
可以看到,yml配置文件结构清晰,层次分明。可以直接用中文字符。
但是!这里需要注意:
- yml文件必须是UTF-8编码格式
- 每行缩进字符都要用空格符,不能用tab字符缩进
- 每个配置项的冒号后边要跟一个空格符
2、新建一个配置文件类用@Component注释,并用@Value注入到类的成员变量中。
package com.example.demo.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class AppProperties2
{
@Value("${com.example.demo.name}")
private String name;
@Value("${com.example.demo.author}")
private String author;
@Value("${com.example.demo.content}")
private String content;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getAuthor()
{
return author;
}
public void setAuthor(String author)
{
this.author = author;
}
public String getContent()
{
return content;
}
public void setContent(String content)
{
this.content = content;
}
}
3、新建一个测试TestController类
package com.example.demo.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.config.AppProperties2;
@RestController
public class TestController2
{
@Autowired
AppProperties2 appProperties2;
@RequestMapping("/test2")
public String showText()
{
// 通过从Spring管理的类中获取配置文件类AppProperties实例,进而获取配置项的值
System.out.println("name=" + appProperties2.getName());
System.out.println("author=" + appProperties2.getAuthor());
System.out.println("content=" + appProperties2.getContent());
return "TestController2!";
}
}
4、启动Spring Boot项目,在浏览器中输入http://localhost:8080/test2/,可以看到控制台打印出来配置项信息: