SpringBoot的congfig文件夹中创建dev和pro文件夹,多个配置文件咋么激活,代码咋么写
时间: 2024-03-07 15:49:53 浏览: 15
在Spring Boot的配置文件夹中,可以按照环境分别创建对应的文件夹,比如dev和pro文件夹分别对应开发环境和生产环境。如果需要在一个环境下加载多个配置文件,可以使用Spring Boot的@PropertySource注解来指定需要加载的配置文件路径,然后使用@Profile注解来指定环境。
下面是示例代码:
在src/main/resources目录下创建config文件夹,然后在config文件夹下创建dev和pro文件夹,分别存放不同环境下的配置文件,如下所示:
```
src/main/resources/
├── config/
│ ├── dev/
│ │ ├── application.properties
│ │ ├── custom.properties
│ │ └── custom.yml
│ ├── pro/
│ │ ├── application.properties
│ │ ├── custom.properties
│ │ └── custom.yml
│ ├── application.properties
│ └── application.yml
```
在代码中使用@PropertySource注解来指定需要加载的配置文件路径,如下所示:
```
@Configuration
@PropertySource({
"classpath:config/${spring.profiles.active}/application.properties",
"classpath:config/${spring.profiles.active}/custom.properties",
"classpath:config/${spring.profiles.active}/custom.yml"
})
public class AppConfig {
// ...
}
```
上述代码中,我们使用了@PropertySource注解来指定需要加载的配置文件路径,其中${spring.profiles.active}表示当前激活的环境。这样,在不同的环境下,Spring会自动加载对应的配置文件。
然后,我们可以使用@Profile注解来指定不同的环境,如下所示:
```
@Configuration
@Profile("dev")
@PropertySource({
"classpath:config/dev/application.properties",
"classpath:config/dev/custom.properties",
"classpath:config/dev/custom.yml"
})
public class DevConfig {
// ...
}
@Configuration
@Profile("pro")
@PropertySource({
"classpath:config/pro/application.properties",
"classpath:config/pro/custom.properties",
"classpath:config/pro/custom.yml"
})
public class ProConfig {
// ...
}
```
上述代码中,我们分别使用@Profile注解指定了dev和pro环境下需要加载的配置文件路径。这样,在不同的环境下,Spring会自动加载对应的配置文件。同时,在启动应用程序时,可以使用--spring.profiles.active参数来指定激活的环境,如下所示:
```
java -jar myapp.jar --spring.profiles.active=pro
```
上述命令将会启动生产环境,并加载pro文件夹下的配置文件。