【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 格式:

file:
  uploadPath: E:/upload

properites 格式:

file.uploadPath=E:/upload

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

@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 读取配置文件

@Data
@Component
@ConfigurationProperties(prefix = "file")
public class FileConfig {
    // 上传路径
    private String uploadPath;
}

3、使用 Environment 读取配置文件

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

@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 配置文件的配置内容

@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 对象读取。

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值