SpringBoot中读取application.yml中的内容

SpringBoot中读取application.yml中的内容

springboot中读取application中的数据是非常简单的,只需创建一个bean,在bean上添加几个注解,然后再定义好对应的属性即可。

1 定义数据

在application中定义数据时不同的文件格式对应不同的数据定义格式,在这里只记录.yml类型的配置文件。
创建一个新的配置文件,取名为application-test.yml。特别注意的是:配置文件的命名规则是application+"-"+“后缀名",前面的application是不能变的,并且如果有后缀名的话还需要在application.yml中声明,声明的格式如下:

spring: 
	profile:
		include: test

只有这样声明了这个配置文件才能在springboot中起作用。
下面开始定义测试数据:

class:
  className: Laker
  men:
    - James
    - Davis
    - Vogel
  role:
    - teacher: Vogel
    - student: Davis,James

2 定义Bean

使用一个Bean来存储从application-test.yml中读取到的内容

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@PropertySource(value = {"classpath:/config/application-test.yml"}, encoding = "utf-8")
@ConfigurationProperties(prefix = "class")
public class Best {
	//对应配置文件中的className
	private String className;
	//对应配置文件中的men
	private List<String> men;
	//对应配置文件中的role
	private List<Map<String, String>> role;
	
	public String getClassName() {
		return className;
	}
	public void setClassName(String className) {
		this.className = className;
	}
	public List<String> getMen() {
		return men;
	}
	public void setMen(List<String> men) {
		this.men = men;
	}
	public List<Map<String, String>> getRole() {
		return role;
	}
	public void setRole(List<Map<String, String>> role) {
		this.role = role;
	}
	
}

类上的三个注解含义分别是:

1.@Component:将当前类声明为一个bean
2.@PropertySource:指定配置文件的路径,这个路径是一个相对路径,具体的要看target目录,比如我的application-test.yml的相对位置是在这里插入图片描述
3.@ConfigurationProperties:指定前缀,具体意思是这个类对应配置文件中的那一部分内容,比如我们指定的前缀是class,则类中的属性对应的是配置文件中class下面的属性;如果不指定的话则对应的是配置文件中的全部内容。

至此所有的工作都做完了,只需启动服务器就能够自动的读取配置文件中的内容。
想要使用这些内容,只需在相应的地方通过@Autowired注解将存储数据的Bean注入一下即可。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值