Spring Boot有3种读取自定义配置的方法,不用自己单独写解析类。

SpringBoot配置项的加载顺序

优先级,从1->4,会互补覆盖。高优先级有的配置会覆盖低优先级的配置。如果同时有propertiesymlproperties的文件优先级高于yml

  1. 项目根目录config的文件夹下的application.properties
  2. 项目根目录下的application.properties
  3. classpath下config文件夹下的application.properties
  4. classpath下的application.properties

当然,在命令行运行的情况下可以指定配置文件 java -jar myproject.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties,或者可以在jar包同目录下放置配置文件,或者同目录config下放置配置文件。classpath:/config/则会加载config目录下的所有配置。

通过Value获取

最常用的方式,通过@Value将配置项注入到成员变量中,最简单。

1
2
@Value("${spring.application.name}")
private String name;

这种只能注入系统配置文件中的配置,如果是自定义的配置文件,如some.properties,那么需要加载这个配置@PropertySource(value = "classpath:some.properties"),这样才能加载出,同样地,下面两种方法也需要指定自定义配置文件。

通过Environment获取

通过注入Environment,然后使用get方法获取配置。

1
2
3
@Resource
private Environment environment;
environment.getProperty("spring.application.name");

通过ConfigurationProperties获取

当需要加载许多配置项的时候,以上两种方法显得很麻烦,要手动将配置项映射到变量上。
本方法可以将同一类的配置文件加载成一个对象。
需要使用到:configuration-metadata-annotation-processor
需要添加依赖:

1
2
3
4
5
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>

根据配置文件定义类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@ConfigurationProperties(prefix="server")
public class ServerProperties {

private String name;

private Host host;

// ... getter and setters

public static class Host {

private String ip;

private int port;

// ... getter and setters
}

}

那么就可以加载如下的配置项:

1
2
3
server.name=localhost
server.host.ip=127.0.0.1
server.host.port=8080