SpringBoot-Yml-松散绑定

我们一般可以通过@Value进行赋值,除了@Value赋值我们还可以使用松散绑定进行赋值,通过yml配置对象,注入到实体类bean中,调用set赋值

yml代码,新建一个student对象:

server:
  port: 8002
student:
  age: 23
  name: "小明啊"

实体类代码:

package com.example.studentspringbootmybatisplus.entity;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component   // 将实体类注入到bean中
@Data   // lombok
@ConfigurationProperties(prefix = "student")   // 对应yml中的对象
public class Student {
    private Integer age;
    private String name;
}

springboot测试代码:

package com.example.studentspringbootmybatisplus;

import com.example.studentspringbootmybatisplus.entity.Student;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class StudentSpringBootMybatisPlusApplicationTests {
    @Autowired
    private Student student;
    @Test
    void contextLoads() {
        System.out.println(student);
    }
}

控制台输出结果代码:

2021-12-10 14:58:59.209  INFO 18752 --- [           main] entSpringBootMybatisPlusApplicationTests : Started StudentSpringBootMybatisPlusApplicationTests in 2.491 seconds (JVM running for 3.549)
Student(age=23, name=小明啊)
2021-12-10 14:58:59.474  INFO 18752 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService 'applicationTaskExecutor'
posted @ 2021-12-10 15:07  HeiDaotu  阅读(129)  评论(0编辑  收藏  举报