1.Spring Boot 的配置文件
spring Boo会自动配置(约定,默认端口8080),可以使用配置文件对默认的配置进行修改。
默认全局配置文件:
- application.properties: key=value
#修改端口号
server.port = 8086
#赋值
student.name=lisi
student.age=28
- application.yml:(不是一个标记文档)key:空格value 或者行内写法(K: V ,[Set/List/数组],{map,对象类型的属性},并且[]可以省略,{}不可以省略)
注意: 1.K:空格V
2.通过位置对齐,指定层次关系
3.默认可以不用写引号;" "会将其中的转移服进行转义,其他不会
student:
name: 张三 #String
age: 21 #int
sex: true #boolean
birthday: 1998/11/01 #Date
location: {province: "广东\n省",city: 汕头市,zone: 潮阳区 } #map图
hobbies: #String[]
[足球,篮球] #行内写法
#- 足球
#- 篮球
skills: #List<String>
- 编程
- 金融
pet: #对象类型Pet
nickName: 旺财
strain: 哈士奇
email: 123456789@qq.com #String
2.通过yaml给对象注入值
- 绑定:
在对象类中添加注解,实现绑定;(具备get and set)
@Component //将此JavaBean放入spring容器中 让 Component Scan 扫描到
@ConfigurationProperties(prefix = "student")//获取yml配置文件中的属性值
//@Validated //开启jsr303数据校验的注解
public class Student {
private String email;
private String name;
private int age;
private boolean sex;
private Date birthday;
//{province:广东省 ,city:汕头市,zone:潮阳区}
private Map<String,Object> location;
private String[] hobbies;
private List<String> skills;
private Pet pet;
表头 | @ConfigurationProperties(prefix = "student") | @Value(“”) 在属性前添加 |
---|---|---|
注值: | 批量注入 | 单个 |
松散语法 | 支持 userName 等价于 user-name | 不支持 |
SpringEL | 不支持 | 支持 “${name}” |
JSR303数据校验 | 支持 | 不支持 |
注入复杂类型 | 支持 | 不支持 |
简单类型:(8个基本类型/Strig/Date)
- 2.注入:
在yml配置文件中,按照格式要求,对属性进行赋值
student:
name: 张三 #String
age: 21 #int
sex: true #boolean
3.@ImportResource(locations={"classpath:spring.xml"}))
spring Boot可以自动装配spring等配置文件,如果自己编写的spring等配置文件,spring boot可以自动识别吗?
默认是不可以识别的,但是可以通过在主配置类中添加该注解,可以识别特定的配置文件。
一般来说,不会推荐使用手写spring配置文件,通过注解进行配置;
@Configuration/*配置类(等价于spring.xml)*/
public class AppConfig {
@Bean
public StudentService studentService(){
StudentService studentService=new StudentService();
return studentService; /*返回值<bean class="xxxx">*/
}
}
4.spring boot全局配置文件中 占位符表达式
${random.uuid} //uuid
${random.int} //随机整数型
${random.value}: //随机字符串
${random.long}: //随机长整型
${random.int(10)}: //10以内的整数型
使用:
1.在application.properties配置文件中定义随机参数
student.name=${random.value}
student.age=${random.int(20)}
2.在application.yml配置文件中引用参数:
student:
name: ${student.name} #String
age: ${student.age}
网友评论