💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
## 一、使用@Value获取配置值 通过@Value注解将family.family-name属性的值绑定到familyName成员变量上面。 ~~~ import lombok.Data; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Data @Component //当我们的类不属于各种归类的时候(不属于@Controller、@Services等的时候),我们就可以使用@Component来标注这个类 public class Family { @Value("${family.family-name}") private String familyName; } ~~~ 在应用启动的时候,从yml文件在读取内容配置到变量中。 可通过测试用例来测试: ~~~ package com.kimgao.bootlauch; import com.kimgao.bootlauch.model.Family; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit.jupiter.SpringExtension; import javax.annotation.Resource; @Slf4j @AutoConfigureMockMvc @SpringBootTest @ExtendWith(SpringExtension.class) public class ValueBeanTest { @Resource Family family; @Test public void valueBeanTest() throws Exception{ System.out.println(family.toString()); } } ~~~ 可看到测试用例打印出了配置文件的内容 ![](https://img.kancloud.cn/4a/22/4a22af967440dd1fe0c7c267c395be05_1135x354.png) ## 二、使用@ConfigurationProperties获取配置值 下面是用于接收上一节中yml配置的java实体类,先不要看我写的代码。测试一下,看看你自己能不能根据yml的嵌套结构,写出来对应的java实体类: ~~~ // 1. 一个家庭有爸爸、妈妈、孩子。 // 2. 这个家庭有一个名字(family-name)叫做“happy family” @Data @Component @ConfigurationProperties(prefix = "family") //表示配置的整体前缀 public class Family { private String familyName; //成员变量名称要和yml配置项key一一对应 private Father father; private Mother mother; private Child child; } ~~~ ~~~ // 3. 爸爸有名字(name)和年龄(age)两个属性 @Data public class Father { private String name; private Integer age; } ~~~ ~~~ // 4. 妈妈有两个别名 @Data public class Mother { private String[] alias; } ~~~ ~~~ //5. 孩子除了名字(name)和年龄(age)两个属性,还有一个friends的集合 @Data public class Child { private String name; private Integer age; private List<Friend> friends; } ~~~ ~~~ // 6. 每个friend有两个属性:hobby(爱好)和性别(sex) @Data public class Friend { private String hobby; private String sex; } ~~~ ## 三、测试用例 写一个测试用例测试一下,看看yml配置属性是否真的绑定到类对象的成员变量上面。 ~~~ // @RunWith(SpringRunner.class) Junit4 @ExtendWith(SpringExtension.class) //Junit5 @SpringBootTest public class CustomYamlTest { @Autowired Family family; @Test public void hello(){ System.out.println(family.toString()); } } ~~~ 测试结果,不能有为null的输出字段,如果有表示你的java实体数据结构写的不正确: ~~~ Family(familyName=happy family, father=Father(name=zimug, age=18), mother=Mother(alias=[lovely, ailice]), child=Child(name=zimug2, age=5, friends=[Friend(hobby=football, sex=male), Friend(hobby=basketball, sex=female)])) ~~~ ![](https://img.kancloud.cn/b1/e6/b1e6c3c6999dc5fecafb82a7535077d1_1826x287.png) ## 四、比较一下二者 | | @ConfigurationProperties | @Value | | --- | --- | --- | | 功能 | 批量注入属性到java类 | 一个个属性指定注入 | | 松散语法绑定 | 支持 | 不支持 | | 复杂数据类型(对象、数组) | 支持 | 不支持 | | JSR303数据校验 | 支持 | 不支持 | | SpEL | 不支持 | 支持 | 数据校验和SPEL的内容,我们后面几节会为大家介绍。