server: port: 80
name: 准JAVA全栈开发工程师server: port: 80# 数组格式likes: - game - movie - music
以配置端口号为例,介绍三种配置文件及其格式。
server.port=80
server: port: 81
server: port: 82
sourceName: SpringBoot server: port: 80 user: name: 准Java全栈开发工程师 age: 22 likes: - music - game - movie
@SpringBootTestclass DemoApplicationTests { @Value("${sourceName}") private String sourceName; @Value("${server.port}") private Integer port; @Value("${user.likes[0]}") private String likes; @Test void contextLoads() { System.out.println(sourceName); System.out.println(port); System.out.println(likes); }}
@SpringBootTestclass DemoApplicationTests { @Autowired private Environment environment; @Test void contextLoads() { System.out.println(environment.getProperty("sourceName")); System.out.println(environment.getProperty("server.port")); System.out.println(environment.getProperty("user.likes[0]")); }}
user: name: 准Java全栈开发工程师 age: 22 likes: - music - game - movie
@Component // 将bean的创建工作交由Spring管理// @ConfigurationProperties 注解表示加载配置文件// 使用prefix前缀表示只加载指定前缀的数据@ConfigurationProperties(prefix = "user")public class User { private String name; private Integer age; private Object[] likes; // get、set、toString和构造器方法省略}
@SpringBootTestclass DemoApplicationTests { @Autowired private User user; @Test void contextLoads() { System.out.println(user); }}
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional></dependency>
原文链接:
https://www.cnblogs.com/qdxorigin/p/16396478.html