怎么在SpringBoot调用yml配置文件

  介绍

怎么在SpringBoot调用yml配置文件?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

<强> 1,yml配置文件书写格式

格式是在普通配置文件中以”。“分割的属性名称,该为“:”和换行。

例子:

//普通格式   spring.datasource.driver-class-name=com.mysql.jdbc.Driver//yml格式   春天:   ,数据源:   driver-class-name才能:com.mysql.jdbc.Driver

注意:

1,在配置文件中的注解格式是

#注解

2,在春天与数据源是相差两个字母的。

3,在属性与值之间有一个冒号和空格,并不是冒号之后直接书写。

<强> 2,在控制器层中取普通键值

以注解@ value(“${属性名}“),来取值。

控制器层取值一般会赋值给属性。

@ value (“$ {offcn_ip}“)   ,private  String 港口;   ,@RequestMapping(“/人)   ,public  String  getOne () {   ,,return 港口;   以前,}

<强> 3,取pojo对象

1,在配置文件中书写一个pojo对象

用户:   ,用户名:zhangsan   ,年龄:23   ,id: 1

2,编写实体类

在实体类中必须有@ConfigurationProperties这个注解,并且指定prrfix前缀。

@ConfigurationProperties (=prefix “user")   public  class  User  {   private 才能String 用户名;   private 才能;Integer 年龄;   private 才能Integer  id;      public 才能;void  setUsername (String 用户名),{   ,,,this.username =,用户名;   ,,}      public 才能;String  getUsername (), {   ,,,return 用户名;   ,,}      public 才能;Integer  getAge (), {   ,,,return 年龄;   ,,}      public 才能;void  setAge (Integer 年龄),{   ,,,this.age =,年龄;   ,,}      public 才能;Integer  getId (), {   ,,,return  id;   ,,}      public 才能;void  setId (Integer  id), {   ,,,this.id =, id;   ,,}      @Override才能   public 才能;String  toString (), {   ,,,return “用户{“+   ,,,,,,,“name=& # 39;“, +, username  +, & # 39; \ & # 39; & # 39; +   ,,,,,,,,,,岁=?+,age  +   ,,,,,,,,,,id=? +, id  +   ,,,,,,,& # 39;}& # 39;;   ,,}   }

3,使用

@RestController   @EnableConfigurationProperties ({User.class})   public  class  Yml  {   @ autowired   User 才能;用户;   @RequestMapping才能(“/人)   public 才能;String  getOne () {   ,,,return  user.toString ();   ,,}   }

EnableConfigurationProperties注解需要加在调用类上,或者加在启动类SpringbootSimpleApplication上也可以。

这就是一个简单的对于yml配置文件中内容的调用,访问请求路径便能获得数据。

看完上述内容,你们掌握怎么在SpringBoot调用yml配置文件的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注行业资讯频道,感谢各位的阅读!

怎么在SpringBoot调用yml配置文件