Spring Boot 是我最近最常用的一个框架了,虽然是约定大于配置,但是你还是得配置一些东西,对于测试和生产环境,可以这样配置。

首先有一个 application-{name}.yml 文件,比如application-setting.yml,用来放一些公共的配置参数,应对产品的各种改动。

cqaso:
  url:
    activeUrl: http://www.cqaso.com/active-veritfy.html
    resetUrl: http://www.cqaso.com/reset-verify.html
  privilege:
    favWord:
      vip:
        total: 200
        one: 20
        count: 0
      user:
        total: 50
        one: 10
        count: 0
    wordBulk:
      vip:
        total: 300
        one: 100
        count: 0
      user:
        total: 50
        one: 20
        count: 0
    appList:
      vip:
        total: 20
        one: 20
        count: 0
      user:
        total: 10
        one: 10
        count: 0

再来一个系统的配置文件,比如数据库啊,端口啊

spring:
  data:
    mongodb:
      uri: mongodb://user:pwd@3.4.5.6:27017/database
  profiles:
    include: setting
server:
  port: 8080

cqaso:
  redis:
    - ip: 1.2.3.4
      auth: pwd
    - ip: 5.6.7.8
      auth: pwd

其中的include 表明,这个配置文件是会把setting配置文件给包含进来的。

运行时指定配置文件只需要

--spring.profiles.active={name}

读取配置文件

这儿用一个不简单,但直观的方法

@Component
@ConfigurationProperties(prefix = "cqaso")
class Config {

    var redis: List<Redis> = mutableListOf()
    var url: Url = Url()
    var privilege: Privileges = Privileges()

    class Redis {
        lateinit var ip: String
        lateinit var auth: String
    }

    class Url {
        lateinit var activeUrl: String
        lateinit var resetUrl: String
    }

    class Privileges {
        var favWord: Privilege = Privilege()
        var wordBulk: Privilege = Privilege()
        var appList: Privilege = Privilege()
        var competitors: Privilege = Privilege()

        class Privilege {
            var user: Detail = Detail()
            var vip: Detail = Detail()

            class Detail {
                var total: Int = 0
                var one: Int = 0
                var count: Int = 0
            }
        }
    }
}

这样就只要注入这个类,其它地方可以直接使用这些配置参数了,我用kotlin就是

config.privilege.wordBulk.vip.one

当然,如果用java,那就是(这样好像一点都不直观)

config.getPrivilege().getWordBulk().getVip().getOne()