yml配置文件获取值,并已json的格式输出

282 阅读1分钟

转载自 www.jianshu.com/p/37306c58a…

原作者:酱油哥_1200   出自简书

项目结构:

![](//upload-images.jianshu.io/upload_images/13231101-e17f3e2b3f697954.png?imageMogr2/auto-orient/strip|imageView2/2/w/543/format/webp)

Person实体类

![](//upload-images.jianshu.io/upload_images/13231101-cefaaeec543c9bac.png?imageMogr2/auto-orient/strip|imageView2/2/w/413/format/webp)

**@ConfigurationProperties(prefix="person")的作用:**告诉SpringBoot将所有的本类所有的属性和配置文件的值进行绑定。

**prefix="person" 前缀的作用:**与配置文件的属性进行配置。如:prefix的值为person ,在application,yml文件中会找到相对应的person属性

**@Component作用:**把该类加载到spring boot容器中

![](//upload-images.jianshu.io/upload_images/13231101-e4506fa8a57ea8c4.png?imageMogr2/auto-orient/strip|imageView2/2/w/339/format/webp)

Dog实体类

![](//upload-images.jianshu.io/upload_images/13231101-6f13b36af068ba62.png?imageMogr2/auto-orient/strip|imageView2/2/w/511/format/webp)

Cotroller控制层:

![](//upload-images.jianshu.io/upload_images/13231101-3540fb269309cc56.png?imageMogr2/auto-orient/strip|imageView2/2/w/707/format/webp)

HelloCotroller.java文件中通过@Autowired注解注入Person 实体类 ,再返回实体类。

**启动项目:**在浏览器输入:http://localhost:8092/hello 将获取yml文件里面的属性值并以JSON格式输出

![](//upload-images.jianshu.io/upload_images/13231101-ed1c3051b469b0c4.png?imageMogr2/auto-orient/strip|imageView2/2/w/974/format/webp)

扩展

![](//upload-images.jianshu.io/upload_images/13231101-6797beb2c33f0177.png?imageMogr2/auto-orient/strip|imageView2/2/w/568/format/webp)

@Validated注解 验证

在Person文件中加入 @Validated注解,并在lastName 属性前面加入@Email 表示lastName 属性值格式必须是 email格式,否则该程序报错

![](//upload-images.jianshu.io/upload_images/13231101-42d884c845616bf8.png?imageMogr2/auto-orient/strip|imageView2/2/w/1200/format/webp)
![](//upload-images.jianshu.io/upload_images/13231101-ffaf042274228ac2.png?imageMogr2/auto-orient/strip|imageView2/2/w/929/format/webp)

作者:酱油哥_1200
链接:www.jianshu.com/p/37306c58a…
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。