SpringBoot.yml配置详解

  • 570
  • 2021年6月24日17:07:31

SpringBoot.yml配置详解:

文件格式

在 spring boot 中,有两种配置文件,一种是application.properties,另一种是application.yml,两种都可以配置spring boot 项目中的一些变量的定义,参数的设置等。下面来说说两者的区别。

application.properties 配置文件在写的时候要写完整,如:

spring.profiles.active=dev
spring.datasource.data-username=root
spring.datasource.data-password=root

在yml 文件中配置的话,写法如下:

spring:
  profiles:
    active: prod
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/test
    username: root
    password: 123456

yml 文件在写的时候层次感强,而且少写了代码。所以现在很多人都使用yml配置文件。

spring配置

spring:
  application:
    name: my-wiki
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/mywiki?characterEncoding=UTF8&&autoReconnect=true&&serverTimezone=Asia/Shanghai
    username: root
    password: 123456
  profiles:
    active: dev

多环境配置

在项目中配置多套环境的配置方法。
因为现在一个项目有好多环境,开发环境,测试环境,准生产环境,生产环境,每个环境的参数不同,所以我们就可以把每个环境的参数配置到yml文件中,这样在想用哪个环境的时候只需要在主配置文件中将用的配置文件写上就行如下:

spring:
  profiles:
    active: prod 

这行配置在application.yml 文件中,意思是当前起作用的配置文件是application_prod.yml,其他的配置文件命名为 application_dev.yml,application_bat.yml等。

设置日志输出

# logging.file 日志输出路径
# logging.level 日志打印级别
logging:
  file: logs/community.log
  level:
    root: info
    org.springframework.web: debug
  file: 
    max-history: 15
    max-size: 100MB

启动参数设置

server:
  prot: 8888  #配置访问的端口
  servlet:
    context-path: /xxx  #配置访问时的项目名

整合Mybatis

spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/test
    driver-class-name: com.mysql.jdbc.Driver
mybatis:
  mapper-locations: classpath:mapping/*Mapper.xml
  type-aliases-package: com.example.entity

整合redis

项目在使用redis时需要先添加依赖然后在配置文件(.yml)中加入一下配置文件,根据自己项目做相应调整

<dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-redis</artifactId>
</dependency>
spring:
  redis:
    host: 127.0.0.1
    port: 6379
    password: 123456
    pool:
      max-active: 100
      max-idle: 10
      max-wait: 100000
    timeout: 0

配置示例

示例1

# 项目相关配置
ruoyi:
  # 名称
  name: RuoYi
  # 版本
  version: 4.6.0
  # 版权年份
  copyrightYear: 2021
  # 实例演示开关
  demoEnabled: true
  # 文件路径 示例( Windows配置D:/ruoyi/uploadPath,Linux配置 /home/ruoyi/uploadPath)
  profile: D:/ruoyi/uploadPath
  # 获取ip地址开关
  addressEnabled: false

# 开发环境配置
server:
  # 服务器的HTTP端口,默认为80
  port: 80
  servlet:
    # 应用的访问路径
    context-path: /
  tomcat:
    # tomcat的URI编码
    uri-encoding: UTF-8
    # tomcat最大线程数,默认为200
    max-threads: 800
    # Tomcat启动初始化的线程数,默认值25
    min-spare-threads: 30

# 日志配置
logging:
  level:
    com.ruoyi: debug
    org.springframework: warn

# 用户配置
user:
  password:
    # 密码错误{maxRetryCount}次锁定10分钟
    maxRetryCount: 5

# Spring配置
spring:
  # 模板引擎
  thymeleaf:
    mode: HTML
    encoding: utf-8
    # 禁用缓存
    cache: false
  # 资源信息
  messages:
    # 国际化资源文件路径
    basename: static/i18n/messages
  jackson:
    time-zone: GMT+8
    date-format: yyyy-MM-dd HH:mm:ss
  profiles: 
    active: druid
  # 文件上传
  servlet:
     multipart:
       # 单个文件大小
       max-file-size:  10MB
       # 设置总上传的文件大小
       max-request-size:  20MB
  # 服务模块
  devtools:
    restart:
      # 热部署开关
      enabled: true

# MyBatis
mybatis:
    # 搜索指定包别名
    typeAliasesPackage: com.ruoyi.**.domain
    # 配置mapper的扫描,找到所有的mapper.xml映射文件
    mapperLocations: classpath*:mapper/**/*Mapper.xml
    # 加载全局的配置文件
    configLocation: classpath:mybatis/mybatis-config.xml

# PageHelper分页插件
pagehelper: 
  helperDialect: mysql
  reasonable: true
  supportMethodsArguments: true
  params: count=countSql 

# Shiro
shiro:
  user:
    # 登录地址
    loginUrl: /login
    # 权限认证失败地址
    unauthorizedUrl: /unauth
    # 首页地址
    indexUrl: /index
    # 验证码开关
    captchaEnabled: true
    # 验证码类型 math 数组计算 char 字符
    captchaType: math
  cookie:
    # 设置Cookie的域名 默认空,即当前访问的域名
    domain: 
    # 设置cookie的有效访问路径
    path: /
    # 设置HttpOnly属性
    httpOnly: true
    # 设置Cookie的过期时间,天为单位
    maxAge: 30
    # 设置密钥,务必保持唯一性(生成方式,直接拷贝到main运行即可)KeyGenerator keygen = KeyGenerator.getInstance("AES"); SecretKey deskey = keygen.generateKey(); System.out.println(Base64.encodeToString(deskey.getEncoded()));
    cipherKey: zSyK5Kp6PZAAjlT+eeNMlg==
  session:
    # Session超时时间,-1代表永不过期(默认30分钟)
    expireTime: 30
    # 同步session到数据库的周期(默认1分钟)
    dbSyncPeriod: 1
    # 相隔多久检查一次session的有效性,默认就是10分钟
    validationInterval: 10
    # 同一个用户最大会话数,比如2的意思是同一个账号允许最多同时两个人登录(默认-1不限制)
    maxSession: -1
    # 踢出之前登录的/之后登录的用户,默认踢出之前登录的用户
    kickoutAfter: false

# 防止XSS攻击
xss: 
  # 过滤开关
  enabled: true
  # 排除链接(多个用逗号分隔)
  excludes: /system/notice/*
  # 匹配链接
  urlPatterns: /system/*,/monitor/*,/tool/*

# Swagger配置
swagger:
  # 是否开启swagger
  enabled: true

示例2

server: 
  port: 8094
spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driverClassName: com.mysql.cj.jdbc.Driver
    url: ${databaseUrl}
    username: ${databaseUsername}
    password: ${databasePassword}
    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
    maxPoolPreparedStatementPerConnectionSize: 20
    filters: stat,wall
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
  redis:
    host: 192.168.1.113
    port: 6379
    timeout: 3600
    cluster:
      nodes: ${redisUrl}
    password: ${redisPassword}
    pool:
      max:
        active: 10
        idle: 8
        wait: -1
pagehelper:
  helperDialect: mysql
  supportMethodsArguments: true
  params: count=countSql
  reasonable: false
eureka:
  client:
    healthcheck:
      enabled: true
  instance:
    leaseRenewalIntervalInSeconds: 10
    leaseExpirationDurationInSeconds: 30
feign:
  hystrix:
    enabled: true

mybatis:
  mapper-locations: classpath:top/quhailong/pan/user/dao/mapping/*.xml
  type-aliases-package: top.quhailong.pan.user.entity

示例3

spring:
  application:
    name: mall-admin
  profiles:
    active: dev #默认为开发环境
  servlet:
    multipart:
      enabled: true #开启文件上传
      max-file-size: 10MB #限制文件上传大小为10M

mybatis:
  mapper-locations:
    - classpath:dao/*.xml
    - classpath*:com/**/mapper/*.xml

jwt:
  tokenHeader: Authorization #JWT存储的请求头
  secret: mall-admin-secret #JWT加解密使用的密钥
  expiration: 604800 #JWT的超期限时间(60*60*24*7)
  tokenHead: 'Bearer '  #JWT负载中拿到开头

redis:
  database: mall
  key:
    admin: 'ums:admin'
    resourceList: 'ums:resourceList'
  expire:
    common: 86400 # 24小时

secure:
  ignored:
    urls: #安全路径白名单
      - /swagger-ui.html
      - /swagger-resources/**
      - /swagger/**
      - /**/v2/api-docs
      - /**/*.js
      - /**/*.css
      - /**/*.png
      - /**/*.ico
      - /webjars/springfox-swagger-ui/**
      - /actuator/**
      - /druid/**
      - /admin/login
      - /admin/register
      - /admin/info
      - /admin/logout
      - /minio/upload

aliyun:
  oss:
    endpoint: oss-cn-shenzhen.aliyuncs.com # oss对外服务的访问域名
    accessKeyId: test # 访问身份验证中用到用户标识
    accessKeySecret: test # 用户用于加密签名字符串和oss用来验证签名字符串的密钥
    bucketName: macro-oss # oss的存储空间
    policy:
      expire: 300 # 签名有效期(S)
    maxSize: 10 # 上传文件大小(M)
    callback: http://39.98.190.128:8080/aliyun/oss/callback # 文件上传成功后的回调地址
    dir:
      prefix: mall/images/ # 上传文件夹路径前缀

minio:
  endpoint: http://192.168.3.101:9090 #MinIO服务所在地址
  bucketName: mall #存储桶名称
  accessKey: minioadmin #访问的key
  secretKey: minioadmin #访问的秘钥

示例4

# 配置项目名和session的过期时间
server:
  servlet:
    context-path: /moti-cloud
    session:
      timeout: 60m
  tomcat:
    uri-encoding: UTF-8
# 日志的存放位置与级别
logging:
  file:
    name: log/moti-cloud.log
  level:
    root: info
# 配置Mybatis
mybatis:
  config-location: classpath:mybatis/mybatis-config.xml
  mapper-locations: classpath:mybatis/mapper/*.xml

spring:
  # 配置邮件任务
  mail:
    username: tangssst@163.com
    password: GRDCGOUASMNEBSTH
    host: smtp.163.com
    port: 465
    properties:
      mail:
        smtp:
          auth: true
          starttls:
            enable: true
            required: true
          socketFactory:
            port: 465
            class: javax.net.ssl.SSLSocketFactory
            fallback: false
  #  静态资源的访问路径
  mvc:
    static-path-pattern: /**
  datasource:
    # 配置数据源
    username: root
    password: 13276785241
    url: jdbc:mysql://127.0.0.1:3306/moti-cloud?serverTimezone=Hongkong&useAffectedRows=true
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    # 配置druid数据源
    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
  # 配置ThymeLeaf模板缓存
  thymeleaf:
    cache: false
  http:
    encoding:
      force: true
      charset: UTF-8
      enabled: true
  # 配置文件上传相关
  servlet:
    multipart:
      max-file-size: 1024MB
      max-request-size: 1024MB
本文来自凡蜕博客(https://blog.ysboke.cn), 转载请带上地址.。
匿名

发表评论

匿名网友