我是靠谱客的博主 冷静高山,这篇文章主要介绍SpringBoot获取yml和properties配置文件的内容,现在分享给大家,希望可以做个参考。

一、yml配置文件

pom.xml加入依赖

复制代码
1
2
3
4
5
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <version>${spring-boot.version}</version> </dependency>
在application.yml文件中加上:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#自定义的属性和值 myYml: simpleProp: simplePropValue arrayProps: 1,2,3,4,5 listProp1: - name: abc value: abcValue - name: efg value: efgValue listProp2: - config2Value1 - config2Vavlue2 mapProps: key1: value1 key2: value2
使用一个java类获取yml文件的内容:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/** * 加载yaml配置文件的方法 * spring-boot更新到1.5.2版本后locations属性无法使用 * @PropertySource注解只可以加载proprties文件,无法加载yaml文件 * 故现在把数据放到application.yml文件中,spring-boot启动时会加载 */ @Component @ConfigurationProperties(prefix = "myYml") public class YmlConfig { String simpleProp; private String[] arrayProps; private List<Map<String, String>> listProp1 = new ArrayList<>(); //接收prop1里面的属性值 private List<String> listProp2 = new ArrayList<>(); //接收prop2里面的属性值 private Map<String, String> mapProps = new HashMap<>(); //接收prop1里面的属性值 get()/set() }

通过依赖注入就可以获取该对象:

复制代码
1
2
@Autowired private YmlConfig config;
二、properties配置文件

使用@PropertySource注解加载配置文件,该注解无法加载yml配置文件。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/** * redis集群配置文件 */ @Component @ConfigurationProperties(prefix = "redis.pool") @PropertySource("classpath:redis.properties") public class RedisProperties { /** redis集群节点 */ private String nodes; /** 连接超时时间 */ private int commandTimeout; /** 重连次数 */ private int maxAttempts; get()/set(); }
通过依赖注入就可以获取该对象:

复制代码
1
2
@Autowired private RedisProperties redisProperties;

最后

以上就是冷静高山最近收集整理的关于SpringBoot获取yml和properties配置文件的内容的全部内容,更多相关SpringBoot获取yml和properties配置文件内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(42)

评论列表共有 0 条评论

立即
投稿
返回
顶部