Spring Boot 2.0 从入门到精通-Profiles

Spring Boot 利用Profile 区分项目中不同环境读取不同的配置文件和代码,最常见的比如:开发和生产环境连接不同数据库。本文以开发环境连接H2,生产连接mysql 为例讲解。阅读本文前最好阅读此文 点击打开链接

在resources目录下添加application-dev.properties,内容如下

#h2
spring.datasource.url=jdbc:h2:file:~/test
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.platform=h2

再添加 application-prod.properties ,内容如下:

#mysql
spring.datasource.url=jdbc:mysql://localhost/form?useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.platform=mysql

如何在项目运行时指定 profile 呢?

1、开发工具是Intellij idea,在run/debug Configurations 界面里可配置,如下图:


2.如果项目打成jar 包的话,在命令行可以添加参数,如:

java -jar spring-boot-demo-profiles-0.0.1-SNAPSHOT.jar --spring.profiles.active=prod

3. 如果在生成环境中不想启动时指定参数,那如何解决呢?

可以这样,在application.properties 中添加 spring.profiles.active=prod

@Profile 的使用

@Profile 可以和@Component 或 @Configuration一起使用,用于根据环境加载相关类,如下: 

@Configuration
@Profile("production")
public class ProductionConfiguration {

	// ...

}

源码下载

======================================

单页表单,简单易用 https://www.dan-ye.com,帮您在线收集各类数据


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值