0
点赞
收藏
分享

微信扫一扫

Spring Boot 配置文件(.properties/yml)

花明 2022-04-14 阅读 80

Spring Boot 配置文件(.properties/yml)

创建一个 Spring Boot工程时,默认resources目录下就有一个application.properties文件,可以在application.properties文件中进行项目配置,但是这个文件并非唯一的配置文件,在Spring Boot中,一共有4 个地方可以存放 application.properties 文件。

  1. 当前项目根目录下的 config 目录下
  2. 当前项目的根目录下
  3. resources 目录下的 config 目录下
  4. resources 目录下
    这四个位置是默认位置,即Spring Boot启动,默认会从这四个位置按顺序去查找相关属性并加载。但是,这也不是绝对的,我们也可以在项目启动时自定义配置文件位置。
    在这里插入图片描述
    项目启动时读取的配置文件位置和文件名可以自定义:
    1、spring.config.location 属性来手动的指定配置文件位置;
    如:java -jar properties-0.0.1-SNAPSHOT.jar --spring.config.location=classpath:/javaboy/
    2、spring.config.additional-location属性来手动的指定配置文件位置,新添加的位置的优先级大于原本的位置;
    如:java -jar properties-0.0.1-SNAPSHOT.jar --spring.config.additional-location=classpath:/javaboy/
    3、spring.config.name 属性指定配置文件名称;
    如:java -jar properties-0.0.1-SNAPSHOT.jar --spring.config.name=app

普通属性的注入:–spring注入方式
如:@Value(“${book.name}”)

# application.properties中配置如下内容:
book.name=笑傲江湖
book.author=金庸
@Component
public class Book {

    @Value("${book.name}")
    private String name;

    @Value("${book.author}")
    private String author;

}

// 可以通过直接@PropertySource指定properties文件
// 如:@PropertySource("clsspath:book.propertis")

类型安全的属性注入:–spring boot注解方式
如:@ConditionalOnProperty(prefix = “book”)
数组注入:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • properties的配置是无序的,ymal的配置是有序的。
举报

相关推荐

0 条评论