1. application.properties
通过application-{profile}.properties的命名规则,给application.properties指定profile,已达到不同的环境使用不同配置的目的。
指定profile的application.properties配置文件会覆盖不指定profile的配置文件,如果有多个profile配置文件,后者覆盖前者。
2. @Profile
任何有@Component和@Configuration注解的class都能添加@Profile注解,以使其仅在指定的环境中生效。如:
@Configuration @Profile("production") public class ProductionConfiguration { // ... }
通常,使用系统属性(spring.profiles.active
) 或操作系统环境变量(SPRING_PROFILES_ACTIVE
)激活profile配置。
使用系统属性,如
$ java -jar -Dspring.profiles.active=production demo-0.0.1-SNAPSHOT.jar
使用spring.profiles.active变量来激活profile,比如在application.properties中指定属性
spring.profiles.active=dev,hsqldb
或者,通过命令行--spring.profiles.active=dev,hsqldb