2、方式一:@Value@SpringBootTestclass DemoApplicationTests {@Value("${sourceName}")private String sourceName;@Value("${server.port}")private Integer port;@Value("${user.likes[0]}")private String likes;@Testvoid contextLoads() {System.out.println(sourceName);System.out.println(port);System.out.println(likes);}}
- 将要读取的数据定义为属性,使用 @Value 注解读取配置文件中的数据并注入给属性,之后在方法体中可以直接使用 。
@SpringBootTestclass DemoApplicationTests {@Autowiredprivate Environment environment;@Testvoid contextLoads() {System.out.println(environment.getProperty("sourceName"));System.out.println(environment.getProperty("server.port"));System.out.println(environment.getProperty("user.likes[0]"));}}- SpringBoot 提供有 Environment 对象,可以将配置文件中的所有数据都封装到该对象中,使用 getProperty 方法,将想要读取的数据名作为参数传入即可 。
user:name: 准Java全栈开发工程师age: 22likes:- music- game- movie- 对于配置类中的 user 数据,其下还有很多子层,如果我们想一下子将 user 的所有数据都取出,应该怎么做呢?将其封装为一个对象 。
@Component// 将bean的创建工作交由Spring管理// @ConfigurationProperties 注解表示加载配置文件// 使用prefix前缀表示只加载指定前缀的数据@ConfigurationProperties(prefix = "user")public class User {private String name;private Integer age;private Object[] likes; // get、set、toString和构造器方法省略}- 和我们定义实体类没有太大的区别,只是这次不再是和数据库表中的字段对应,而是和配置文件中定义的数据对应 。
- 除此之外,还需要使用 ConfigurationProperties 注解加载配置文件,使用 prefix 指定加载数据的前缀 。
@SpringBootTestclass DemoApplicationTests {@Autowiredprivate User user;@Testvoid contextLoads() {System.out.println(user);}}- 使用该方式在定义实体类时,会报红提示

文章插图
- 我们只需要在 pom.xml 文件中导入相应的依赖即可 。
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-configuration-processor</artifactId><optional>true</optional></dependency>原文链接:
https://www.cnblogs.com/qdxorigin/p/16396478.html
推荐阅读
- 朋友圈走心文案范文 关于圣诞的朋友圈温暖文案2021
- 我与老师发生的趣事作文,关于和老师之间发生的事情的作文-
- 怎么讲教育孩子的心得,关于如何教育孩子的心得-
- 洗头发每天洗好吗,每天都洗头好嘛-
- 描写岳飞精忠报国的诗,岳飞的诗句关于精忠报国-
- 恭王府的福碑故事,关于恭王府的福字碑的来历-
- 关于饮食和减肥的论文
- 水浒传中的杨志是一个怎样的人,水浒传中关于杨志的-
- 正月里不能理发吗-,正月里不可以理发吗-
- 扁鹊一共活了几年 扁鹊活了多少年?
