如何为Spring Boot Profiles设置默认值

   2024-09-30 8300
核心提示:在 Spring Boot 中,可以通过以下方法为 profiles 设置默认值:使用 spring.profiles.default 属性在 application.properties 或

在 Spring Boot 中,可以通过以下方法为 profiles 设置默认值:

使用 spring.profiles.default 属性

application.propertiesapplication.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” 作为默认配置文件。

 
举报打赏
 
更多>同类维修大全
推荐图文
推荐维修大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号