配置maven中的 profiles 属性,分为开发环境 dev 和生产环境 prod
<profiles> <profile> <id>dev</id> <activation> <activeByDefault>true</activeByDefault> </activation> <properties> <environment>dev</environment> </properties> </profile> <profile> <id>prod</id> <activation> <activeByDefault>false</activeByDefault> </activation> <properties> <environment>prod</environment> </properties> </profile> </profiles>
在build属性中设置好 application.yml,用 ${environment} 来识别 dev 或者 prod
<build> <resources> <resource> <directory>src/main/resources</directory> <excludes> <exclude>application*.yml</exclude> </excludes> </resource> <resource> <directory>src/main/resources</directory> <filtering>true</filtering> <includes> <include>application.yml</include> <include>application-${environment}.yml</include> </includes> </resource> </resources> </build>
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
@Profiles注解可以为一个特定的bean指定环境,使用方法如下:
@Bean @Profile("dev")
这样,这个bean就被指定为使用dev环境配置,即只有在dev环境激活的情况下才会创建这个bean。
也可以使用@Profile(“!xxx”)来指定不使用某种配置,意味着只要不激活某种配置就要创建这个bean。