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 + '\'' +
                ", age=" + age +
                ", id=" + id +
                '}';
    }
}

3、使用

@RestController
@EnableConfigurationProperties({User.class})
public class Yml {
  @Autowired
    User user;
    @RequestMapping("/one")
    public String getOne(){
        return user.toString();
    }
}

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

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

猜你喜欢

转载自www.cnblogs.com/xueziyeya/p/11808135.html