温馨提示×

springboot怎么加载指定配置文件

小亿
90
2024-01-16 20:18:54
栏目: 编程语言

Spring Boot可以通过@ConfigurationProperties注解来加载指定的配置文件。具体步骤如下:

  1. 在项目的resources目录下,创建一个配置文件,比如application-dev.properties,其中dev为指定的环境名称。

  2. 在Spring Boot项目的配置类上添加@ConfigurationProperties注解,并设置prefix属性为配置文件中的前缀,比如"spring.datasource"。同时设置locations属性为配置文件的路径,比如"classpath:application-${spring.profiles.active}.properties"。

示例代码如下:

@Configuration
@ConfigurationProperties(prefix = "spring.datasource")
@PropertySource(value = {"classpath:application-${spring.profiles.active}.properties"})
public class DataSourceConfig {
    private String url;
    private String username;
    private String password;

    // getters and setters
}
  1. 在pom.xml文件中添加如下依赖:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>
  1. 在application.properties或application.yml文件中设置"spring.profiles.active"属性为指定的环境,比如"dev"。
spring.profiles.active=dev

或者

spring:
  profiles:
    active: dev

这样,Spring Boot就会根据指定的配置文件加载对应的配置信息。

0