SpringBoot中的配置文件与配置读取(二)

SpringBoot中如何读取配置文件的值+配置文件怎么设置默认值+读取自定义配置文件

代码示范

Test

1
2
3
4
5
6
7
8
9
10
11
12
13
@SpringBootTest
public class ReadYml {

@Resource
private TestConfig testConfig;

@Test
public void readYml() {
System.out.println("使用Bean读取:"+testConfig.getMyConfigByMethod());
System.out.println("使用Lombok读取:"+testConfig.getMyConfig());
System.out.println("使用Lombok读取1:"+testConfig.getMyConfig1());
}
}

Config配置类读取yml中的配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Configuration
@Data
public class TestConfig {

@Value("${wahoyu.my-config:defaultConfig}")
private String myConfig;

@Value("${wahoyu.my-config1:defaultConfig}")
private String myConfig1;

@Bean
public String getMyConfigByMethod() {
return myConfig;
}

}

yml配置文件

1
2
3
# 测试属性专用
wahoyu:
my-config: fromYml

测试结果

总结

  1. Config配置类可以使用@Data注解获取里面注入的属性,并不一定非要用@Bean注解啊
  2. yml配置文件中的值,优先级大于设置的default默认值,如果yml中没有值才会读取到这个default值

@PropertySource注解

额外读取其他位置的自定义配置文件,并不会替换掉原来的配置文件,可以添加很多配置文件

从soup口中我们知道了一个新的注解名字叫@PropertySource

这个注解有几个注意事项:

  1. 只能读取.properties文件
  2. 可以自定义properties文件的位置,不一定非要指定在resource文件夹下
  3. 可以自定义文件的名称,不一定非得叫application.properties
  4. 这个注解可以添加多个properties配置文件进来

配置文件路径:

1
wahoyu.wahoyu-properties = "wahoyuProperties"

读取配置文件:

1
2
3
4
5
6
7
8
@Configuration
@PropertySource("classpath:properties/wahoyu.properties")
@Data
public class TestProperties {

@Value("${wahoyu.wahoyu-properties}")
private String myConfig;
}

运行测试代码:

1
2
3
4
@Test
public void readProperties() {
System.out.println("读取:"+testProperties.getMyConfig());
}

@PropertySource注解添加多文件

一个类上可以添加多个 @PropertySource 注解,这样可以加载多个配置文件。每个 @PropertySource 注解指定一个 .properties 文件,Spring 会依次加载这些文件中的属性。

1
2
3
4
5
6
7
8
@SpringBootApplication
@PropertySource("classpath:properties/file1.properties")
@PropertySource("classpath:properties/file2.properties")
public class MySpringBootApplication {
public static void main(String[] args) {
SpringApplication.run(MySpringBootApplication.class, args);
}
}

还有一种简便的方法是使用 @PropertySources 组合注解:

1
2
3
4
5
6
7
8
9
10
@SpringBootApplication
@PropertySources({
@PropertySource("classpath:properties/file1.properties"),
@PropertySource("classpath:properties/file2.properties")
})
public class MySpringBootApplication {
public static void main(String[] args) {
SpringApplication.run(MySpringBootApplication.class, args);
}
}

📌就算我们只添加一个@PropertySource注解,这个配置文件也是能读取到原来的配置文件的


SpringBoot中的配置文件与配置读取(二)
http://wahoyu.xyz/2024/07/10/SpringBootConfig/
作者
Wahoyu
发布于
2024年7月10日
许可协议