springboot读取配置文件(application.properties)的优先级

没看过实现读取配置文件的代码,无非就是两种.

1.优先读取内部配置文件加载配置项,然后再读取外部配置文件,如果有相同的配置项则进行覆盖替换.

2.优先读取外部配置文件加载配置项,然后再读取内部配置文件,如果对象配置项已经存在则跳过,不存在则进行加载.

配置优先级

1.在jar包的同一目录下建一个config文件夹,然后把application.properties放在这个文件夹内

2.在jar包的同一目录下放入application.properties文件

3.在classpath下建一个config文件夹,然后把配置文件放进去

4.在classpath下将配置文件放进去

项目使用读取对应的配置项,可在成员属性上直接使用@Value注解,即可读取,如下面示例

1
2
@Value("${key}")
private String configPropertyValue;

如果需要读取注入进静态属性上,可使用set方法进行配置并且在类上需要使用注解声明此实例(如注解@Component,@Configuration),直接在静态属性上使用@Value注解是无效的,如下面示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package com.jiange.threadpooltest.httpclient;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class SpringValueUtil {

private static String hostname;

private static String cookieId;

private static String date;

private static String templateId;

private static String subject;

public static String getHostname() {
return hostname;
}

@Value("${springValueUtil.hostname}")
public void setHostname(String hostname) {
SpringValueUtil.hostname = hostname;
}

public static String getCookieId() {
return cookieId;
}

@Value("${springValueUtil.cookieId}")
public void setCookieId(String cookieId) {
SpringValueUtil.cookieId = cookieId;
}

public static String getDate() {
return date;
}

@Value("${springValueUtil.date}")
public void setDate(String date) {
SpringValueUtil.date = date;
}

public static String getTemplateId() {
return templateId;
}

@Value("${springValueUtil.templateId}")
public void setTemplateId(String templateId) {
SpringValueUtil.templateId = templateId;
}

public static String getSubject() {
return subject;
}

@Value("${springValueUtil.subject}")
public void setSubject(String subject) {
SpringValueUtil.subject = subject;
}

}

对应的application.properties文件是

1
2
3
4
5
springValueUtil.hostname=localhost:8091
springValueUtil.cookieId=JSESSIONID=876AE921BA4BA17A0DC3497080BD2425
springValueUtil.date=2023-01-01
springValueUtil.templateId=8aa02d185d4f90d3015d4fbd11de04ae
springValueUtil.subject=1

还需注意的是使用时需要先调用SpringApplication.run方法,进行启动springboot项目才会加载对应配置文件,如图:

springboot关于server配置的相关说明参考博客

server.xxx配置

https://blog.csdn.net/qq_15028299/article/details/86499417