如何把properties里面的配置绑定到JavaBean里面,以前我们的做法如下:
输出结果:
key=human.name——————value=Mr.Yukey=human.age——————value=21key=human.gender——————value=male
Process finished with exit code 0
可以看到这个过程十分繁杂,但是在SpringBoot中这个过程将会变得非常简单。
在SpringBoot中有如下3种方法:
1.@ConfigurationProperties注解+@Component(或@Controller或@Service或@Repository)注解
只有在容器中的组件,才会拥有SpringBoot提供的强大功能,也就是如果我们需要使用到@ConfigurationProperties注解,那么我们首先要保证该对JavaBean对象在IoC容器中,所以需要用到Component注解来添加组件到容器中。@ConfigurationProperties注解中prefix与value互相都是别名 也就是说@ConfigurationProperties(value = "human")与@ConfigurationProperties(prefix = "human")是一样的prefix和value指的是前缀的意思代码测试: properties配置文件:
Person类:
测试类如下:
测试结果:
@ConfigurationProperties注解+@EnableConfigurationProperties注解
这种方式@EnableConfigurationProperties注解一定要在配置类上写,@EnableConfigurationProperties的意思是开启属性配置功能,开启谁的属性配置功能呢,因为我们上面的Person类想进行配置绑定,所以我们在后面加上参数Person.class:@EnableConfigurationProperties(Person.class)
@EnableConfigurationProperties(Person.class)的作用就是把这个Person组件注册到容器中,对象的名称为:human-com.ysw.boot.properties.Person 其中human是@ConfigurationProperties(value = "human")中前缀value的值
在Person类上还是有@ConfigurationProperties注解,这种方式把Person类上的@Component注解换成了配置类上的@EnableConfigurationProperties(Person.class)注解
这种方式主要用在引用第三方包时,比如第三方包中有一个Person类,该类中没有使用@Component,我们也不能够给第三方包中的类加上@Component,这个时候就可以使用在配置类上加上@EnableConfigurationProperties注解的方法。
@ConfigurationProperties注解+@Import注解
使用@Import给容器中自动创建出这个类型的组件、默认组件的名字就是全类名@Import注解与2中的@ConfigurationProperties注解效果是一样的只不过他们注册到容器中的名称不同:@ConfigurationProperties注解注册到容器中对象的名称为:human-com.ysw.boot.properties.Person 其中human是@ConfigurationProperties(value = "human")中前缀value的值@Import注解注册到容器中对象的名称为:com.ysw.boot.properties.Person配置类:
Person类:
测试类:
application.properties文件:
测试结果:
到此这篇关于SpringBoot中@ConfigurationProperties注解实现配置绑定的三种方法的文章就介绍到这了,更多相关SpringBoot配置绑定方法内容请搜索七叶笔记以前的文章或继续浏览下面的相关文章希望大家以后多多支持七叶笔记!