温馨提示×

如何为Spring Boot Profiles设置默认值

小樊
83
2024-08-30 05:03:04
栏目: 编程语言

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

  1. 使用 spring.profiles.default 属性

application.propertiesapplication.yml 文件中,添加以下配置:

# application.properties
spring.profiles.default=dev

或者

# application.yml
spring:
  profiles:
    default: dev

这将设置默认的活动配置文件为 “dev”。如果没有指定其他活动配置文件,Spring Boot 将使用 “dev” 作为默认配置文件。

  1. 使用命令行参数

在启动 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'
  1. 使用 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” 作为默认配置文件。

0