SpringBoot快速开发
概述
1.提供了一种快速开发Spring项目的方式,不是对Spring功能上的增强
2.自动配置,依赖传递
快速入门
1.创建Maven项目
2.导入SpringBoot起步依赖
3.定义Controller
4.编写引导类
5.启动测试
自动配置原理
pom.xml
- spring-boot-dependencies:核心依赖在父工程中
- springBoot依赖不用指定版本
启动器(SpringBoot启动场景)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
- spring-boot-web会帮我们自动导入web所有依赖
- springboot会把所有功能场景变为启动器
- 使用功能只需要找到启动器
主程序SpringApplication
@SpringBootApplication
public class HelloApplication {
public static void main(String[] args) {
SpringApplication.run(HelloApplication.class,args);
}
}
- 注解
@SpringBootConfiguration @Configuration:spring配置类 @Component:spring组件 @EnableAutoConfiguration:自动配置 @AutoConfigurationPackage @Import({Registrar.class}) @Import({AutoConfigurationImportSelector.class}):自动导入选择 //获取所有的配置 List<String> configurations = this.getCandidateConfigurations(annotationMetadata, attributes);
SpringApplication
@SpringBootApplication
//启动了一个服务,而不是一个服务
SpringApplication.run(HelloApplication.class,args);
- 判断是普通项目还是web项目
- 推断当前的主类
yaml语法
将空格作为分割符,对空格的要求很高
server:
//普通的键值对
port: 8080 (key: value)
//普通对象
student:
name: langzhizhen
age: 22
//行内写法
student: {name: langzhizhen,age: 22}
//数组
pets:
- cat
- dog
- pig
pets: [cat,dog,pig]
yaml可以直接给实体类赋值,使用
//将配置文件中的值与JavaBean的值一一对应
@ConfigurationProperties(prefix = "类名")
//测试类中自动装配
@Autowired
private Person person;
SpEL表达式
@Value("hello")
private String word;//将hello赋值给word
@Value("http://www.baidu.com")
private Resource url;//赋值网址
@Value("${book.author}")
private String author; //properties资源文件内的配置项
使用 @Value(${}) 格式时,spring会通过加载框架自带的 PropertySourcesPlaceholderConfigurer 的Bean,或者通过 @PropertySource 制定特定的properties文件
JSR303校验
@Validated//在JavaBean中数据校验