我是靠谱客的博主 搞怪帆布鞋,这篇文章主要介绍【SpringBoot】SpringBoot 读取配置文件中的自定义属性的 5 种方法,现在分享给大家,希望可以做个参考。

SpringBoot 配置文件的格式有两种:yml、properties。有些方法都适用,但有些方法就有针对性了。

概括地说,Spring Boot 中读取配置文件有以下 5 种方法:

  1. 使用 @Value 读取配置文件(yml、properties)
  2. 使用 @ConfigurationProperties 读取配置文件(yml、properties)
  3. 使用 Environment 读取配置文件(yml、properties)
  4. 使用 @PropertySource 读取配置文件(yml、properties)
  5. 使用 原生方式 读取配置文件(properties)

如:配置文件内容:

yml 格式:

复制代码
1
2
3
file: uploadPath: E:/upload

properites 格式:

复制代码
1
2
file.uploadPath=E:/upload

1、 使用 @Value 读取配置文件

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@SpringBootApplication public class Application implements InitializingBean{ @Value("${file.uploadPath}") private String profileName; public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Override public void afterPropertiesSet() throws Exception { System.out.println(profileName); } }

2、使用 @ConfigurationProperties 读取配置文件

复制代码
1
2
3
4
5
6
7
8
@Data @Component @ConfigurationProperties(prefix = "file") public class FileConfig { // 上传路径 private String uploadPath; }

3、使用 Environment 读取配置文件

将此类使用 @Autowired 注入到类中就可以使用它的 getProperty() 方法来获取某个配置项的值了

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@SpringBootApplication public class Application implements InitializingBean{ @Autowired private Environment environment; public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Override public void afterPropertiesSet() throws Exception { System.out.println(environment.getProperty("file.uploadPath")); } }

4、使用 @PropertySource 读取配置文件
使用 @PropertySource 注解可以用来指定读取某个配置文件,比如指定读取 application.yml 配置文件的配置内容

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@SpringBootApplication @PropertySource("classpath:application.yml") public class Application implements InitializingBean{ @Value("${file.uploadPath}") private String path; public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Override public void afterPropertiesSet() throws Exception { System.out.println(path); } }

5、使用 原生方式 读取配置文件(properties)

就是使用 Properites 对象读取。

最后

以上就是搞怪帆布鞋最近收集整理的关于【SpringBoot】SpringBoot 读取配置文件中的自定义属性的 5 种方法的全部内容,更多相关【SpringBoot】SpringBoot内容请搜索靠谱客的其他文章。

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

评论列表共有 0 条评论

立即
投稿
返回
顶部