Spring Boot基础 - application.properties配置详解 - 03

Spring Boot中的application.properties主要用来配置数据库连接、日志相关配置等。除了这些配置内容之外,
本文将具体介绍一些在application.properties配置中的其他特性和使用方法。

1.自定义属性与加载

我们在使用Spring Boot的时候,通常也需要定义一些自己使用的属性,我们可以如下方式直接定义:

	demo.url=baidu.com
	demo.key=what is spring boot
	#甚至可以采用组合的方式,讲上面两个字符内容进行了拼接
	demo.completeurl=${demo.url}?k=${demo.key}

然后通过@Value("${属性名}")注解来加载对应的配置属性,具体如下:

@Component
public class BlogProperties {
    @Value("${demo.url}")
    private String url;
    @Value("${demo.key}")
    private String key;
    @Value("${demo.completeurl}")
    private String completeurl;
    // 省略getter和setter
}

2.产生随机数

在一些情况下,有些参数我们需要希望它不是一个固定的值,比如密钥、服务端口等。Spring Boot的属性配置文件中可以通过${random}来产生int值、long值或者string字符串,来支持属性的随机值。

# 随机字符串
com.value=${random.value}
# 随机int
com.number=${random.int}
# 随机long
com.bignumber=${random.long}
# 10以内的随机数
com.test1=${random.int(10)}
# 10-20的随机数
com.test2=${random.int[10,20]}

3.多环境配置

我们在开发Spring Boot应用时,通常同一套程序会被应用和安装到几个不同的环境,比如:开发、测试、生产等。其中每个环境的数据库地址、服务器端口等等配置都会不同,如果在为不同环境打包时都要频繁修改配置文件的话,那必将是个非常繁琐且容易发生错误的事。

在Spring Boot中多环境配置文件名需要满足application-{profile}.properties的格式,其中{profile}对应你的环境标识,比如:

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

需要引入哪一个配置,则只需更改一个地方

#test则匹配application-test.properties文件,其他同理
spring.profiles.active=test

最后附上一些spring boot 常见的配置信息

#程序启动后端口号
server.port=8889

#多环境配置
spring.profiles.active=test

#mysql连接配置
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

#整体编码设置
spring.http.encoding.force=true
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
server.tomcat.uri-encoding=UTF-8

#thymeleaf模板配置
#配置返回路径
spring.thymeleaf.prefix=classpath:/templates/  
#匹配的后缀
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8;charset=UTF-8
spring.thymeleaf.content-type=text/html
#是否缓存到浏览其,测试环境下建议false
spring.thymeleaf.cache=false  

# redis整体设置
# Redis数据库索引(默认为0)
spring.redis.database=0  
# Redis服务器地址
spring.redis.host=192.168.0.58
# Redis服务器连接端口
spring.redis.port=6379  
# Redis服务器连接密码(默认为空)
spring.redis.password=  
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=8  
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1  
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=8  
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0  
# 连接超时时间(毫秒)
spring.redis.timeout=0  
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值