使用到的注解
- @EnableAutoConfiguration
- @ConfigurationProperties(prefix = “person”)
- @ProipertySource(value = {“classpath:person.properties”})
- @Validated
使用到的属性
- spring.profiles.active
- spring.profiles(多文档块时使用)
- debug
命令行参数
- spring.config.location(指定配置文件位置)
- spring.profiles.active(激活指定环境配置)
值的写法
字面量:普通的值(数字,字符串,布尔)
k: v:字面直接来写;
字符串默认不用加上单引号或者双引号;
“”:双引号;不会转义字符串里面的特殊字符;特殊字符会作为本身想表示的意思
name: “zhangsan \n lisi”:输出;zhangsan 换行 lisi
‘’:单引号;会转义特殊字符,特殊字符最终只是一个普通的字符串数据
name: ‘zhangsan \n lisi’:输出;zhangsan \n lisi
对象、Map(属性和值)(键值对):
k: v:在下一行来写对象的属性和值的关系;注意缩进
对象还是k: v的方式
friends:
lastName: zhangsan
age: 20
行内写法:
friends: {
lastName: zhangsan,age: 18}
数组(List、Set):
用- 值表示数组中的一个元素
pets:
- cat
- dog
- pig
行内写法
pets: [cat,dog,pig]
值注入
配置文件
person:
age: 18
name: fgr
sex: true
prices: [1.2,1.3,99.99]
meta: {
age: 2,name: dog}
children: [{
age: 1,name: "fgr\nmh"},{
age: 2,name: 'fgr\nmh'}]
实体类
@Data
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
private int age;
private String name;
private boolean sex;
private List<Double> prices;
private Map<String, String> meta;
private List<Person> children;
}
pom文件
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!--自定义配置时生成与类对应的提示-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
测试
@RunWith(SpringRunner.class)
@SpringBootTest
class HelloWorldApplicationTest {
@Autowired
Person person;
@Test
void hello() {
System.out.println(person);
}
}
结果
Person(age=18, name=fgr, sex=true, prices=[1.2, 1.3, 99.99], meta={age=2, name=dog}, children=[Person(age=1, name=fgr
mh, sex=false, prices=null, meta=null, children=null), Person(age=2, name=fgr\nmh, sex=false, prices=null, meta=null, children=null)])
properties文件方式
properties文件
person.age=18
person.name=fgr
person.sex=true
person.prices=1.3,1.4
person.meta.age=2
person.meta.name=dog
person.children[0].age=2
person.children[0].name=dog
person.children[1].age=3
person.children[1].name=cat
实体类
@Data
@Component
@ConfigurationProperties(prefix = "person")
@PropertySource(value = {
"classpath:person.properties"}) //指定配置文件
public class Person {
private int age;
private String name;
private boolean sex;
private List<Double> prices;
private Map<String, String> meta;
private List<Person> children;
}
数据验证
实体类
@Data
@Component
@ConfigurationProperties(prefix = "person")
@PropertySource(value = {
"classpath:person.properties"})
@Validated 开启验证
public class Person {
private int age;
private String name;
@Email 验证方式
private String email;
private boolean sex;
private List<Double> prices;
private Map<String, String