温馨提示×

springboot怎么读取多个配置文件

小亿
97
2024-01-18 13:43:46
栏目: 编程语言

在Spring Boot中,可以通过@PropertySource注解来读取多个配置文件。

Step 1: 创建多个配置文件

src/main/resources目录下创建多个配置文件,比如config1.propertiesconfig2.properties

Step 2: 创建配置类

在Spring Boot应用的配置类中使用@PropertySource注解来指定要读取的配置文件,代码示例如下:

@Configuration
@PropertySource({"classpath:config1.properties", "classpath:config2.properties"})
public class AppConfig {

    // 使用@Value注解来读取配置文件中的值
    @Value("${property1}")
    private String property1;

    @Value("${property2}")
    private String property2;

    // ...

    // 其他配置和方法
}

在上面的示例中,@PropertySource注解指定了要读取的配置文件路径,可以同时指定多个配置文件。

Step 3: 使用配置值

在需要使用配置值的地方,可以通过@Value注解来读取配置文件中的值,例如:

@Service
public class MyService {

    @Value("${property1}")
    private String property1;

    // ...

    // 其他代码
}

在上面的示例中,@Value注解用于读取property1配置项的值。

注意:如果有多个配置文件中存在相同的配置项,后面的配置文件中的配置项会覆盖前面的配置文件中的配置项。

0