关于spring boot的YAML 配置文件( 二 )

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 注解读取配置文件中的数据并注入给属性,之后在方法体中可以直接使用 。
3、方式二:Environment@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 方法,将想要读取的数据名作为参数传入即可 。
4、方式三:自定义对象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);}}
  • 使用该方式在定义实体类时,会报红提示

关于spring boot的YAML 配置文件

文章插图
 
  • 我们只需要在 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




推荐阅读