当前位置:   article > 正文

SpringBoot (配置文件)_springboot 项目 yml文件变为普通文件

springboot 项目 yml文件变为普通文件

1 简介

      SpringBoot中免除了大部分手动配置,但是对于一些特定的情况,还是需要我们进行手动配置的,SpringBoot为我们提供了application.properties配置文件,让我们可以进行自定义配置,来对默认的配置进行修改,以适应具体的生产情况,当然还包括一些第三方的配置。几乎所有配置都可以写到application.peroperties文件中,这个文件会被SpringBoot自动加载,免去了我们手动加载的烦恼。

1、配置文件的格式

  SpringBoot可以识别两种格式的配置文件,分别是yml文件与properties文件,我们可以将application.properties文件换成application.yml,这两个文件都可以被SpringBoot自动识别并加载,但是如果是自定义的配置文件,就最好还是使用properties格式的文件,因为SpringBoot中暂时还并未提供手动加载yml格式文件的功能(这里指注解方式)。

  application.properties配置文件欲被SpringBoot自动加载,需要放置到指定的位置:src/main/resource目录下,一般自定义的配置文件也位于此目录之下。

2、配置文件的加载

  加载的意思就是将文件读取到Spring容器之中,更确切的说就是将各个配置项装载到Spring上下文容器之中供随时取用。

  application.properties配置文件是在SpringBoot项目启动的时候被自动加载的,其内部的相关设置会自动覆盖SpringBoot默认的对应设置项,所以的配置项均会保存到Spring容器之中。

以application.yml 为例

项目结构

 

2 pom 配置

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-web</artifactId>
  4. </dependency>
  5. <dependency>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-test</artifactId>
  8. <scope>test</scope>
  9. </dependency>

3 yml 配置

  1. server:
  2. port: 8088
  3. student:
  4. name: Jack
  5. age: 22
  6. birth: 1990/12/12

4 Conroller 类

  1. package com.example.springbootporperties.conroller;
  2. import org.springframework.beans.factory.annotation.Value;
  3. import org.springframework.stereotype.Controller;
  4. import org.springframework.web.bind.annotation.RequestMapping;
  5. import org.springframework.web.bind.annotation.ResponseBody;
  6. import java.util.Date;
  7. @Controller
  8. public class TestController {
  9. @Value("${student.name}")
  10. private String name;
  11. @Value("${student.age}")
  12. private Integer age;
  13. @Value("${student.birth}")
  14. private Date date;
  15. @ResponseBody
  16. @RequestMapping("/student")
  17. public String hello() {
  18. return " name=" +name + " age=" +age +" date=" +date;
  19. }
  20. }

5 启动项目

 

6浏览器访问

http://localhost:8088/student

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/239483
推荐阅读
相关标签
  

闽ICP备14008679号