Spring Boot 2.x (二):Spring Boot 基础配置

  • 2019 年 11 月 6 日
  • 筆記

在 Spring Boot 中,配置文件有两种不同的格式,一种是 properties ,另一种是 yaml。

application.properties 格式如下:

#redis 配置  spring.redis.host=127.0.0.1  spring.redis.port=6379  spring.redis.timeout=6s

application.yml 格式如下:

spring:    #redis配置    redis:      host: 127.0.0.1      port: 6379      timeout: 6s #连接池超时时长

当我们创建一个 Spring Boot 工程时,默认 resources 目录下就有一个 application.properties 文件,可以在 application.properties 文件中进行项目配置。接下来,本文将介绍在 Spring Boot 项目开发过程中与配置相关的一些知识。

第一个 Web 应用 Hello Spring Boot 2 这篇文章中,我们已经介绍通过修改 Spring Boot 项目的全局配置文件,来解决端口冲突问题。当然除了 server.port 属性之外,Spring Boot 官方还提供了很多可配置的属性,感兴趣的小伙伴可以访问 spring-boot/common-application-properties 网页查看完整的可配置属性信息。

一、自定义属性

1.1 @Value 注解

Spring Boot 允许我们在 application.properties 下自定义一些属性,比如:

person.name=semlinker  person.sex=1

接着定义一个 Person 类:

@Data  @Component  public class Person {      @Value("${person.name}")      private String name;        @Value("${person.sex}")      private Integer sex;  }

为了能够在浏览器或其它 Http 客户端,验证是否能成功注入属性,我们来创建一个 PersonController 类:

@RestController  public class PersonController {      @Autowired      private Person person;        @RequestMapping("/person")      String index() {          return "My name is " + person.getName() + " and my sex is " +                  person.getSex();      }  }

下面启动应用,等启动成功后,使用浏览器访问 http://localhost:8080/person 地址,如果一切顺利的情况下,页面上会显示以下内容:

My name is semlinker and my sex is 1

很明显,我们的自定义属性已经成功注入了。通过 @Value("${person.name}") 这种方式注入自定义属性的方式,对于少量属性还好,若需要注入的属性非常多的情况下,若继续使用这种方式,开发起来会很费劲。针对这种情形,我们可以 @ConfigurationProperties 注解来简化上述过程。

1.2 @ConfigurationProperties 注解

首先在 application.properties 文件中新增以下内容:

blog.name=semlinker's blog  blog.title=spring boot 2.x

接着定义一个 Blog 类:

当在 Idea 中输入以上代码时,Idea 会提示 Spring Boot Configuration Annotation Processor not found in classpath,同时引导我们打开 spring-boot/configuration-metadata-annotation-processor 页面,进入该页面后,我们看到了以下信息:

You can easily generate your own configuration metadata file from items annotated with @ConfigurationProperties by using the spring-boot-configuration-processor jar. The jar includes a Java annotation processor which is invoked as your project is compiled. To use the processor, include a dependency on spring-boot-configuration-processor.

由此可知 spring-boot-configuration-processor 的作用是编译时生成 spring-configuration-metadata.json 文件, 此文件主要给 IDE 使用,用于提示使用。因此我们在 pom.xml 中添加 spring-boot-configuration-processor 的坐标:

<dependency>  	<groupId>org.springframework.boot</groupId>  	<artifactId>spring-boot-configuration-processor</artifactId>  	<optional>true</optional>  </dependency>

当导入 spring-boot-configuration-processor 后,我们来完善一下前面定义的 Blog 类:

@Data  @ConfigurationProperties(prefix = "blog")  @Component  public class Blog {      private String name;        private String title;  }

与前面定义 PersonController 的步骤一样,我们同样也来定义一个 BlogController 类:

@RestController  public class BlogController {      @Autowired      private Blog blog;        @RequestMapping("/blog")      public String index() {          return "My blog name is " + blog.getName() +                  " and title is " + blog.getTitle();      }    }

之后我们重启应用,使用浏览器访问 http://localhost:8080/blog 地址,此时页面显示如下:

My blog name is semlinker's blog and title is spring boot 2.x

现在我们已经知道了如何获取 application.properties 中自定义一些属性,需要注意的是,属性之间是可以相互引用的,具体如下:

blog.name=semlinker's blog  blog.title=spring boot 2.x  blog.fullTitle=${blog.name}-${blog.name}

二、自定义配置文件

除了可以在 application.properties 里配置属性,我们还可以自定义一个配置文件。在 src/main/resources 目录下新建一个 user.properties:

user.age=4  user.birth=2015/02/14  user.last-name=lolo  user.boss=true  user.dog.name=yoyo  user.dog.age=1  user.maps.k1=v1  user.maps.k2=v2  user.lists=a,b,c

接着分别创建相应的 User 类和 Dog 类:

User 类
@Data  @Configuration  @ConfigurationProperties(prefix = "user")  @PropertySource("classpath:user.properties")  public class User {      private String lastName;      private Integer age;      private Boolean boss;      private Date birth;      private Map<String, Object> maps;      private List<Object> lists;      private Dog dog;  }
Dog 类
@Data  public class Dog {      private String name;      private Integer age;  }

同样继续创建一个 UserController 类:

@RestController  public class UserController {        @Autowired      User user;        @RequestMapping("/user")      public String index() {          return user.toString();      }  }

最后重启应用,等启动成功后,使用浏览器访问 http://localhost:8080/user 地址,此时页面显示如下:

User(lastName=lolo, age=4, boss=true, birth=Sat Feb 14 00:00:00 CST 2015, maps={k2=v2, k1=v1}, lists=[a, b, c], dog=Dog(name=yoyo, age=1))

三、多环境配置

Spring Boot 的多环境配置文件名需要满足 application-{profile}.properties 的格式,{profile} 对应你的环境 比如新建三个配置文件:

  • application-dev.properties —— 开发环境 server.port=8080
  • application-test.properties —— 测试环境 server.port=8081
  • application-prod.properties —— 生产环境 server.port=8082

至于哪个具体的配置文件会被加载,需要在 application.properties 文件中通过 spring.profiles.active 属性来设置,其值对应 {profile} 值,比如:

spring.profiles.active=prod

前面三种方式都是基于配置文件层面的,那么有没有办法外部引导呢,假设这样的场景,我们对已经开发完成的代码打包发布,期间在测试环境测试通过了,那么即可发布上生产,这个时候是修改 application.properties 的配置方便还是直接通过命令参数配置方便呢,毫无疑问是后者更便捷。默认情况下,SpringApplication 会将命令行选项参数(即:–property,如–server.port=9000)添加到 Environment,命令行属性始终优先于其他属性源。

四、集成第三方依赖

集成第三方其实特别简单,比如 Redis,步骤如下:

  1. pom.xml 中引入 starter 对应的 redis 依赖 —— spring-boot-starter-data-redis:
<dependency>      <groupId>org.springframework.boot</groupId>      <artifactId>spring-boot-starter-data-redis</artifactId>  </dependency>
  1. application.properties 配置文件中配置相关属性
spring.redis.host=127.0.0.1  spring.redis.port=6379  spring.redis.timeout=6s

项目地址:https://github.com/semlinker/springstack/tree/master/springboot2-configuration

五、总结

@ConfigurationProperties@Value 都是 Spring 提供的用于从配置文件注入配置信息的方式。很显然,@Value 比较适用于配置比较少的场景,而 @ConfigurationProperties 则更适用于有很多配置的情况。

此外 @ConfigurationProperties 是可以和 validation 注解一起使用的,这样的好处显而易见:对于一些配置是必须的或者是对格式有要求的,在运行开始的时候就能检测到这些问题,这样就可以避免上线之后因为配置问题导致系统异常的问题。比如:

@Component  @Getter  @Setter  @ToString  @ConfigurationProperties(prefix = "oauth")  public class PropertiesConfiguration {      @NotBlank      private String clientId;      @NotBlank      private String clientSecret;      @URL      private String redirectUri;      @NotBlank      private String grantType;  }

@PropertySource 注解,目的是加载自定义配置文件,如本文中的 user.properties 文件。