在 Spring Boot 中,可以通过以下方法为 profiles 设置默认值:
使用spring.profiles.default 属性在 application.properties 或 application.yml 文件中,添加以下配置:
# application.propertiesspring.profiles.default=dev或者
# application.ymlspring: profiles: default: dev这将设置默认的活动配置文件为 “dev”。如果没有指定其他活动配置文件,Spring Boot 将使用 “dev” 作为默认配置文件。
使用命令行参数在启动 Spring Boot 应用程序时,可以通过命令行参数设置默认的配置文件。例如:
java -jar yourapp.jar --spring.profiles.default=dev或者,当使用 Maven 或 Gradle 运行应用程序时:
mvn spring-boot:run -Dspring-boot.run.arguments=--spring.profiles.default=dev或者
gradle bootRun --args='--spring.profiles.default=dev'使用 Programmatic 方式设置在 Spring Boot 应用程序中,可以编程方式设置默认的配置文件。创建一个实现 org.springframework.boot.SpringApplicationRunListener 接口的类,并覆盖 environmentPrepared 方法,如下所示:
import org.springframework.boot.SpringApplication;import org.springframework.boot.SpringApplicationRunListener;import org.springframework.core.env.ConfigurableEnvironment;import org.springframework.core.env.PropertiesPropertySource;public class DefaultProfileApplicationRunListener extends SpringApplicationRunListener { public DefaultProfileApplicationRunListener(SpringApplication application, String[] args) { super(application, args); } @Override public void environmentPrepared(ConfigurableEnvironment environment) { if (!environment.getPropertySources().contains("classpath:/application.yml")) { Properties defaultProperties = new Properties(); defaultProperties.put("spring.profiles.default", "dev"); PropertiesPropertySource propertySource = new PropertiesPropertySource("defaultProperties", defaultProperties); environment.getPropertySources().addLast(propertySource); } }}然后,需要在 src/main/resources/META-INF/spring.factories 文件中注册此自定义 SpringApplicationRunListener:
org.springframework.boot.SpringApplicationRunListener=com.example.DefaultProfileApplicationRunListener这样,在没有指定其他活动配置文件时,Spring Boot 将使用 “dev” 作为默认配置文件。


