Spring Boot配置文件解析

Spring Boot使用了一个全局的配置文件application.properties,放在src/main/resources目录下或者类路径的/config下。Sping Boot的全局配置文件的作用是对一些默认配置的配置值进行修改。

接下来,让我们一起来解开配置文件的面纱。

注:如果你工程没有这个application.properties,那就在src/main/java/resources目录下新建一个。

一、自定义属性

application.properties提供自定义属性的支持,这样我们就可以把一些常量配置在这里:

com.dudu.name="嘟嘟MD"
com.dudu.want="祝大家鸡年大吉吧"

然后直接在要使用的地方通过注解@Value(value="${config.name}")就可以绑定到你想要的属性上面

@RestController
public class UserController {

    @Value("${com.dudu.name}")
    private  String name;
    @Value("${com.dudu.want}")
    private  String want;

    @RequestMapping("/")
    public String hexo(){
        return name+","+want;
    }
}

我们启动工程输入http://localhost:8080就可以看到打印了”嘟嘟MD,祝大家鸡年大吉吧”。

有时候属性太多了,一个个绑定到属性字段上太累,官方提倡绑定一个对象的bean,这里我们建一个ConfigBean.java类,顶部需要使用注解@ConfigurationProperties(prefix = “com.dudu”)来指明使用哪个

@ConfigurationProperties(prefix = "com.dudu")
public class ConfigBean {
    private String name;
    private String want;

    // 省略getter和setter
}

这里配置完还需要在spring Boot入口类加上@EnableConfigurationProperties并指明要加载哪个bean,如果不写ConfigBean.class,在bean类那边添加@PropertySource("classpath:application.properties")

@SpringBootApplication
@EnableConfigurationProperties({ConfigBean.class})
public class Chapter2Application {

    public static void main(String[] args) {
        SpringApplication.run(Chapter2Application.class, args);
    }
}

最后在Controller中引入ConfigBean使用即可,如下:

@RestController
public class UserController {
    @Autowired
    ConfigBean configBean;

    @RequestMapping("/")
    public String hexo(){
        return configBean.getName()+configBean.getWant();
    }
}

2.参数间引用

在application.properties中的各个参数之间也可以直接引用来使用,就像下面的设置:

com.dudu.name="嘟嘟MD"
com.dudu.want="祝大家鸡年大吉吧"
com.dudu.yearhope=${com.dudu.name}在此${com.dudu.want}

这样我们就可以只是用yearhope这个属性就好

3.使用自定义配置文件

有时候我们不希望把所有配置都放在application.properties里面,这时候我们可以另外定义一个,这里我明取名为test.properties,路径跟也放在src/main/resources下面。

com.md.name="哟西~"
com.md.want="祝大家鸡年,大吉吧"

我们新建一个bean类,如下:

@Configuration
@ConfigurationProperties(prefix = "com.md") 
@PropertySource("classpath:test.properties")
public class ConfigTestBean {
    private String name;
    private String want;
    // 省略getter和setter
}

4.随机值配置

配置文件中${random} 可以用来生成各种不同类型的随机值,从而简化了代码生成的麻烦,例如 生成 int 值、long 值或者 string 字符串。

dudu.secret=${random.value}
dudu.number=${random.int}
dudu.bignumber=${random.long}
dudu.uuid=${random.uuid}
dudu.number.less.than.ten=${random.int(10)}
dudu.number.in.range=${random.int[1024,65536]}

5.外部配置-命令行参数配置

Spring Boot是基于jar包运行的,打成jar包的程序可以直接通过下面命令运行:

java -jar xx.jar

可以以下命令修改tomcat端口号:

java -jar xx.jar --server.port=9090

可以看出,命令行中连续的两个减号--就是对application.properties中的属性值进行赋值的标识。
所以java -jar xx.jar --server.port=9090等价于在application.properties中添加属性server.port=9090。
如果你怕命令行有风险,可以使用SpringApplication.setAddCommandLineProperties(false)禁用它。

6.Profile-多环境配置

当应用程序需要部署到不同运行环境时,一些配置细节通常会有所不同,最简单的比如日志,生产日志会将日志级别设置为WARN或更高级别,并将日志写入日志文件,而开发的时候需要日志级别为DEBUG,日志输出到控制台即可。
如果按照以前的做法,就是每次发布的时候替换掉配置文件,这样太麻烦了,Spring Boot的Profile就给我们提供了解决方案,命令带上参数就搞定。

这里我们来模拟一下,只是简单的修改端口来测试
在Spring Boot中多环境配置文件名需要满足application-{profile}.properties的格式,其中{profile}对应你的环境标识,比如:

  • application-dev.properties:开发环境
  • application-prod.properties:生产环境

想要使用对应的环境,只需要在application.properties中使用spring.profiles.active属性来设置,值对应上面提到的{profile},这里就是指dev、prod这2个。

当然你也可以用命令行启动的时候带上参数:

java -jar xxx.jar --spring.profiles.active=dev

我给不同的环境添加不同的端口属性server.port,然后根据指定不同的spring.profiles.active来切换使用。

除了spring.profiles.active来激活一个或者多个profile之外,还可以用spring.profiles.include来叠加profile

spring.profiles.active: testdb  
spring.profiles.include: proddb,prodmq

附录A.常用应用程序属性

http://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html
开发中的application.yml文件

spring:
  profiles:
    active: pro

开发中的application-dev.yml文件

spring:
  application:
    name: ums
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: org.postgresql.Driver
    username: postgres
    password: postgres
    url: jdbc:postgresql://192.168.1.87:49902/${spring.application.name}
    druid:
      dup-close-log-enable: true
      initial-size: 0
      max-active: 24
  jpa:
    generate-ddl: true
    open-in-view: true
    show-sql: true
    hibernate:
      ddl-auto: update
      use-new-id-generator-mappings: false
    properties:
      hibernate.format_sql: true
      hibernate.generate_statistics: false
      hibernate.max_fetch_depth: 2
      hibernate.jdbc.fetch_size: 50
      hibernate.jdbc.batch_size: 50
      hibernate.cache.use_second_level_cache: true
      hibernate.cache.use_structured_entries: true
      hibernate.cache.use_query_cache: true
      hibernate.cache.region.factory_class: org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory
      javax.persistence.sharedCache.mode: ENABLE_SELECTIVE
      hibernate.temp.use_jdbc_metadata_defaults: false
      hibernate.dialect: org.hibernate.dialect.PostgreSQLDialect
  data:
    web:
      pageable:
        default-page-size: 20
        max-page-size: 100
        page-parameter: page
        size-parameter: size
      sort:
        sort-parameter: sort
    mongodb:
      uri: mongodb://192.168.1.87:49901/ums
  servlet:
    multipart:
      enabled: true
      max-file-size: 50MB
      max-request-size: 100MB
  http:
    converters:
      preferred-json-mapper: jackson
    encoding:
      force: true
      charset: UTF-8
      enabled: true
    log-request-details: true
  jackson:
    date-format: yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
    locale: zh_CN
    time-zone: UTC
server:
  port: 49988
logging:
  level:
    cn.swifthealth: debug
    com.jfinal: debug
dream:
  weixin:
    access-token-cache: access-token-cache
    dev-mode: true
    url-patterns: /weixin/**
    wx-configs:
      - appId: wx88369f95502c5c98
        appSecret: d6987a7a696c6a9df9e060091841daca
        token: wx

你可能感兴趣的:(Spring Boot配置文件解析)