8、Spring Boot:使用application.yml配置文件

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/,可以看到控制台打印出来配置项信息:

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值