Spring Boot 学习1.2--yml文件配置与读取

SpringBoot中支持在yml文件里面进行数据的配置与获取的操作,在yml文件里面都是一对对键值(key:value)关系的数据。

首先在项目文件的resource路径下面创建一个名为application的yml文件,如图:

       然后我们可以在yml文件里面配置服务器端口号:

server:
  port: 8000

然后在主文件夹下面创建bean文件夹,创建Student类和Teacher类:

  在Student类中编写以下代码,设置属性

@Component
@ConfigurationProperties(prefix = "student")
public class Student {
    private String Name;
    private Integer age;
    private Boolean pass;
    private Date birth;

    private Map<String,Object> maps;
    private List<Object> lists;
    private Teacher teacher;

使用@Component注解表示这是一个组件,使用ConfigurationProperties(prefix = "student")进行组件的动态绑定,prefix = "student"语句表示配置文件中下面的所有属性进行映射,将配置文件的每一个属性的值映射到这个组件中,然后使用alt+insert设置setter和getter方法以及toString()方法。效果如下:

,然后在Teacher类里面写以下代码,不需要注解,但是需要按以上方法设置getter and getter方法以及toSting()所有的属性。
public class Teacher {
    private String name;
    private int age;
    private String level;
    private String sex;

在pom.xml文件中添加以下的依赖,导入配置文件处理器,然后重新运行springboot项目就可以成功运行了

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

然后在yml文件中写入以下数据,提供组件进行读取:

student:
    Name: 窃格瓦拉
    age: 21
    pass: true
    birth: 1998/09/02 18:00:00
    maps: {k1 : v1,k2 : v2}
    lists:
      - 林欢
      - 蔡女士
    teacher:
      name: 超威男猫
      age: 30
      level: 叫兽
      sex: ♂

然后在test目录的主程序Test文件中,进行spring boot单元测试,实例化Student类,将组件从yml文件中获取的数据打印

@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {

    @Autowired
    Student student;

    @Test
    public void contextLoads() {
        System.out.println(student);
    }

}

点击该文件中的启动按钮进行测试,输出结果如下:

发布了58 篇原创文章 · 获赞 31 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/qq_37504771/article/details/95248036
今日推荐