SpringBoot学习笔记(上)
SpringBoot 配置
小结
SpringBoot提供了2种配置文件类型: properteis和yml / yaml
默认配置文件名称:application
同一级目录下优先级为: properties>yml>yaml
YAML小结
配置文件类型
(1)properties:和以前一样
yml/yaml:注意空格
(2) yaml: 简洁,以数据为核心
- 基本语法
- 大小写敏感
- 数据值前边必须有空格,作为分隔符
- 使用空格缩进表示层级关系,相同缩进表示同一级
- 数据格式
- 对象
- 数组:使用“_”表示数组每个元素
- 纯量
- 参数引用
$ikey)
server:
port: 8083
name: abc
# 对象
person:
name: ${name}
age: 20
# 行内对象写法
person2: {name: scc, age: 20}
#数组
address:
- xian
- beijing
# 行内数组写法
address2: [xian,beijing]
# 纯量
msg1: 'hello \n world'
msg2: "hello \n world"
读取配置内容
- @Value
- Environment
- @ConfigurationProperties
-
(1) @Value("${name}") private String name; @Value("${person.name}") private String name2; @Value("${person.age}") private int age; @Value("${address[0]}") private String address1; @Value("${msg1}") private String msg1; @Value("${msg2}") private String msg2; (2) @Autowired private Environment env; System.out.println(env.getProperty("address[1]")); (3) @ConfigurationProperties(prefix = "person")ps:
Test文件无法使用runwith注解的解决方法
引入下面依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
</dependency>
-
/** * * 测试类 * */ @RunWith(SpringRunner.class) @SpringBootTest(classes = SpringbootTestApplication.class) public class UserServiceTest { @Autowired private UserService userService; @Test public void testADdd(){ userService.add(); } }
...全文



