您的当前位置:首页SpringBoot中yml配置文件

SpringBoot中yml配置文件

来源:小侦探旅游网
SpringBoot中yml配置⽂件

1、yml配置⽂件书写格式

  格式是在普通配置⽂件中以“.”分割的属性名称,该为“: ”和换⾏。  例⼦:

//普通格式

spring.datasource.driver-class-name=com.mysql.jdbc.Driver//yml格式spring:

datasource:

driver-class-name: com.mysql.jdbc.Driver

  注意:

    1、在配置⽂件中的注解格式是      #注解

    2、在spring与dataSource是相差两个字母的。

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

2、在controller层中取普通键值

  以注解@Value(\"${属性名}\"),来取值。  controller层取值⼀般会赋值给属性。

@Value(\"${offcn_ip}\") private String port; @RequestMapping(\"/one\") public String getOne(){ return port; }

3、取pojo对象

  1、在配置⽂件中书写⼀个pojo对象

user:

username: zhangsan age: 23 id: 1

  2、编写实体类

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

@ConfigurationProperties(prefix = \"user\")public class User {

private String username; private Integer age; private Integer id;

public void setUsername(String username) { this.username = username; }

public String getUsername() { return username; }

public Integer getAge() { return age; }

public void setAge(Integer age) { this.age = age; }

public Integer getId() { return id; }

public void setId(Integer id) { this.id = id; }

@Override

public String toString() { return \"User{\" +

\"name='\" + username + '\\'' + \ \ '}'; }}

3、使⽤

@RestController

@EnableConfigurationProperties({User.class})public class Yml {  @Autowired User user;

@RequestMapping(\"/one\") public String getOne(){ return user.toString(); }}

EnableConfigurationProperties注解需要加在调⽤类上,或者加在启动类SpringbootSimpleApplication上也可以。这就是⼀个简单的对于yml配置⽂件中内容的调⽤,访问请求路径便能获得数据。

因篇幅问题不能全部显示,请点此查看更多更全内容