Springboot官网学习(6、深入Springboot之外部化配置【三yml配置项绑定到实体Bean】)

由于上节:Springboot官网学习(6、深入Springboot之外部化配置【三使用yaml代替properties】)讲到yaml可以使用yml,作为程序员,一切从简,所以后面就以yml来讲了

我们应该知道spring中,如果想要把properties中配置的值,绑定到我们的config实体中,通常使用的是@Value注解来实现,
springboot中的properties中,也是通过@Value来实现的。

不过yml文件,如果绑定在config实体中,官方不建议使用@Value注解,因为存在像如下的配置:

zyxx:
	company:
		name: "gs"
		age: 4
	person:
		count: 25
		maxAge: 30
		minAge: 20

像这种,company和person是同级的,他们各自有各自的属性,正常情况下,我们可能会这样定义我们的config类

public class Zyxx{

	private final Company company;
	private final Person persony;
	
	public static class Company{
		private final String name;
		private final String age;
		// get/set省略
	}
	
	public static class Person{
		private final int count;
		private final int maxAge;
		private final int minAge
		// get/set省略
	}
}

这种如果我们使用@Value来实现的话,确实是有点繁琐了,
那么springboot提供了两种方式来进行轻松绑定,并且还会类型检查

1、实体set绑定

@ConfigurationProperties(prefix),此注解打在实体上面,那么他就会将配置文件里面的配置通过set方法注入进去。

@Component
@ConfigurationProperties("zyxx")
public class Zyxx{

	private final Company company;
	private final Person persony;
	
	public static class Company{
		private final String name;
		private final String age;
		// get/set省略
	}
	
	public static class Person{
		private final int count;
		private final int maxAge;
		private final int minAge
		// get/set省略
	}
}
2、构造函数绑定(此种方式需要@EnableConfigurationProperties来开启)

个人建议@EnableConfigurationProperties注解打在启动类上,自动扫码启动类下面的,

@SpringBootApplication
@EnableConfigurationProperties
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}
@Component
@ConstructorBinding
@ConfigurationProperties("zyxx")
public class Zyxx{
	public Zyxx(Company company, Person person){
		this.company = company;
		this.person = person;
	}
	private final Company company;
	private final Person persony;
	
	public static class Company{
		private final String name;
		private final String age;
		// get/set省略
	}
	
	public static class Person{
		private final int count;
		private final int maxAge;
		private final int minAge
		// get/set省略
	}
}

看了两种绑定的方式,是不是觉得简单多了。springboot还是一切从简,为开发者节省了很多时间啊!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值