springboot 读取配置文件

一.读取springboot 自带的application.properties或application.yml文件

1.通过@Value注解来读取

application.properties文件内容:

name=1

user.name=2

读取方式:

@Value("${name}")
private String name;
 
@Value("${user.name}")
private String userName;

 如果要设置默认值:

@Value("${name:张三}")
private String name;
 
//设置默认值为空置
@Value("${user.name:#{null}}")
private String userName;

 2.通过@ConfigurationProperties(prefix="***")来读取

@Data
@Component
@ConfigurationProperties(prefix="user")
public class TestBean{
 
    String name;
}

二.读取springboot中自定义的properties文件,例如test.properties

1.通过@Value和@PropertySource结合取值

复制代码
@Component
@PropertySource("classpath:test.properties")
public class TestBean{
 
    @Value("${name}")
    private String name;
 
    @Value("${user.name}")
    private String userName;
}
复制代码

2.通过@ConfigurationProperties和@PropertySource结合取值

@Component
@ConfigurationProperties(prefix="user")
@PropertySource("classpath:test.properties")
public class TestBean{
    String name;
}

 

posted @   Bonnie_ξ  阅读(370)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2021-08-11 spring boot 启动加载 CommandLineRunner @PostConstruct
2021-08-11 @PostConstruct 注解详解
2021-08-11 springboot 中CommandLineRunner接口的作用
点击右上角即可分享
微信分享提示