博客
关于我
SpringBoot | 读取yaml配置文件并注入JavaBean
阅读量:373 次
发布时间:2019-03-04

本文共 1006 字,大约阅读时间需要 3 分钟。

如果我们有一个类Person

public class Person {       public String name;    public int age;    public Date birthday;    public Map
map; public List
list; //getter和setter和toString()略}

在resources文件夹下用applications.yml

person:  name: zhangsan  age: 20  birthday: 2020/11/1  map:    k1: v1    k2: v2  list:    - aaa    - bbb    - ccc

现在我们要做的就是:读取这个yml文件的信息,并注入到Person类里,并打印出来。

  1. 先在pom.xml里导入一个依赖(这一步好像不是必须的)
org.springframework.boot
spring-boot-configuration-processor
  1. 给Person类加上以下注解:
@Component@ConfigurationProperties(prefix = "person")

其中perfix参数需要和配置文件里的那个key值匹配,@Component的作用是将这个对象加入到Spring的IOC容器中。

  1. 测试
    在测试类中(src的test文件夹下),创建一个Person对象,并用@AutoWired注入,然后打印结果。
@SpringBootTestclass DemoApplicationTests {       @Autowired    Person person;    @Test    void contextLoads() {           System.out.println(person);    }}
  1. 输出结果,打印出以下内容表示注入成功!
Person{name='zhangsan', age=20, birthday=Sun Nov 01 00:00:00 CST 2020, map={k1=v1, k2=v2}, list=[aaa, bbb, ccc]}

转载地址:http://yayg.baihongyu.com/

你可能感兴趣的文章
Nginx 反向代理+负载均衡
查看>>
Nginx 反向代理解决跨域问题
查看>>
Nginx 反向代理配置去除前缀
查看>>
nginx 后端获取真实ip
查看>>
Nginx 多端口配置和访问异常问题的排查与优化
查看>>
Nginx 如何代理转发传递真实 ip 地址?
查看>>
Nginx 学习总结(16)—— 动静分离、压缩、缓存、黑白名单、性能等内容温习
查看>>
Nginx 学习总结(17)—— 8 个免费开源 Nginx 管理系统,轻松管理 Nginx 站点配置
查看>>
Nginx 学习(一):Nginx 下载和启动
查看>>
nginx 常用指令配置总结
查看>>
Nginx 常用配置清单
查看>>
nginx 常用配置记录
查看>>
nginx 开启ssl模块 [emerg] the “ssl“ parameter requires ngx_http_ssl_module in /usr/local/nginx
查看>>
Nginx 我们必须知道的那些事
查看>>
Nginx 源码完全注释(11)ngx_spinlock
查看>>
Nginx 的 proxy_pass 使用简介
查看>>
Nginx 的 SSL 模块安装
查看>>
Nginx 的优化思路,并解析网站防盗链
查看>>
Nginx 的配置文件中的 keepalive 介绍
查看>>
nginx 禁止以ip形式访问服务器
查看>>