清音洞--Spring系列之读取配置信息注解(六)

本章小宋简单介绍一下Spring的配置注解。

读取配置信息注解

很多时候我们需要将一些常用的配置信息比如阿里云 oss 配置、发送短信的相关信息配置等等放到配置文件中。

下面我们来看一下 Spring 为我们提供了哪些方式帮助我们从配置文件中读取这些配置信息。

配置文件内容如下:

server:
  port: 8080
  tomcat:
    max-swallow-size: -1
  servlet:
    context-path: /vyun
    compression:
      enabled: true
      mime-types: application/javascript,application/json,application/xml,text/html,text/xml,text/plain,text/css,image/*

management:
  endpoints:
    web:
      exposure:
        include: metrics,httptrace

spring:
  servlet:
    multipart:
      max-file-size: 1024MB
      max-request-size: 1024MB
  
  ## quartz定时任务,采用数据库方式
  quartz:
    job-store-type: jdbc
  #json 时间戳统一转换
  jackson:
    date-format:   yyyy-MM-dd HH:mm:ss
    time-zone:   GMT+8
    #接口返回的数据中不含value为null的key
    #default-property-inclusion: non_null

使用 @Value("${property}") 读取

@Value

@Value我们常用来读取比较简单的配置信息

@Value("${server.port}")
int port;

@ConfigurationProperties

使用@ConfigurationProperties读取配置信息并与 bean 绑定。

@Component
@ConfigurationProperties(prefix = "spring.servlet.multipart")
public class MultipartProperties {
    @NotEmpty
    private String maxFileSize; // 配置文件中是max-file-size, 转驼峰命名便可以绑定成
    private String maxRequestSize;

  省略getter/setter
  ......
}

你可以像使用普通的 Spring bean 一样,将其注入到类中使用。

@PropertySource

这个注解不怎么常用,但还是讲一下。
@PropertySource读取指定 properties 文件

@Component
@PropertySource("classpath:config.properties")
public class Config {
    @Value("${url}")
    private String url;

  省略getter/setter
  ......
}

讲到这里本章对Spring读取配置信息注解的讲解也就结束了,如果想了解更多知识可以在对应的专栏中看系列文章,谢谢大家的观看,希望能给各位同学带来帮助。如果觉得博主写的还可以的,可以点赞收藏。 😉

posted @ 2020-12-03 17:07  奋斗的小宋  阅读(32)  评论(0)    收藏  举报