SpringBoot profiles 实现多环境配置
SpringBoot profiles 实现多环境配置
1. maven配置
配置maven中的 profiles 属性,分为开发环境 dev 和生产环境 prod
<profiles> <profile> <id>devid> <activation> <activeByDefault>trueactiveByDefault> activation> <properties> <environment>devenvironment> properties> profile> <profile> <id>prodid> <activation> <activeByDefault>falseactiveByDefault> activation> <properties> <environment>prodenvironment> properties> profile> profiles> 在build属性中设置好 application.yml,用 ${environment} 来识别 dev 或者 prod
<build> <resources> <resource> <directory>src/main/resourcesdirectory> <excludes> <exclude>application*.ymlexclude> excludes> resource> <resource> <directory>src/main/resourcesdirectory> <filtering>truefiltering> <includes> <include>application.ymlinclude> <include>application-${environment}.ymlinclude> includes> resource> resources> build> 2. application.yml配置
application.yml 中的设置:利用 spring.profiles.active 属性获取 @environment@ 变量的值
spring: profiles: active: '@environment@' 下面是 application-dev.yml 中的配置,上面的 ${environment} 能获取是 dev 还是 prod,获取后赋值给变量 environment,再由上面的@environment@ 确定使用的是哪一个application的配置
spring: mail: host: smtp.163.com username: 148181684116@163.com password: WEEASPCPAKDXSPDDFWEASW datasource: url: jdbc:mysql://localhost:3306/book_manager?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8 username: root password: 123456 driver-class-name: com.mysql.cj.jdbc.Driver jpa: show-sql: true hibernate: ddl-auto: update mvc: pathmatch: matching-strategy: ant_path_matcher 3. @Profiles注解
@Profiles注解可以为一个特定的bean指定环境,使用方法如下:
@Bean @Profile("dev") 这样,这个bean就被指定为使用dev环境配置,即只有在dev环境激活的情况下才会创建这个bean。
也可以使用@Profile(“!xxx”)来指定不使用某种配置,意味着只要不激活某种配置就要创建这个bean。