文章目录
SpringBoot
一、SpringBoot的作用
- 简化配置文件
- 以更简单的方式整合第三方技术
- Redis
- ElasticSearch
- MyBatis
- ……
二、使用SpringBoot的套路
- 加入需要的场景starter依赖
- 配置properties或yml
- 创建主启动类
- 通过注解开启相关功能
- 运行主启动类
三、HelloWorld
1.操作步骤
①创建Maven工程
②加入依赖
<!-- 继承SpringBoot官方指定的父工程 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
</parent>
<dependencies>
<!-- 加入Web开发所需要的场景启动器 -->
<dependency>
<!-- 指定groupId和artifactId即可,版本已在父工程中定义 -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
③创建主启动类
④创建HelloHandler
@Controller
public class HelloHandler {
@ResponseBody
@RequestMapping("/hello")
public String hello() {
return "Hello SpringBoot!";
}
}
⑤启动
运行主启动类中的main方法启动SpringBoot程序。
⑥通过网页访问handler方法
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4rAZbVoJ-1575439557738)(images/p04.png)]
2.通过Spring插件创建SpringBoot工程
限制:每次创建工程都必须联网;必须借助Spring插件。
3.原理探究
①核心机制
②重要注解
注解名称 | 作用 |
---|---|
@SpringBootApplication | 声明一个SpringBoot程序,并使 @SpringBootConfiguration @EnableAutoConfiguration @ComponentScan 等注解生效 |
@SpringBootConfiguration | 相当于@Configuration注解的重新定义 |
@Configuration | 声明一个Spring配置类 |
@Bean | 在@Configuration注解标记的类中将标记了@Bean的方法返回值对象加入IOC容器,可以对应XML配置文件中的bean标签来理解 |
@EnableAutoConfiguration | 启用自动配置 |
@AutoConfigurationPackage | 当前包下包含需要自动扫描的类 |
@ComponentScan | 指定要扫描的包 |
四、SpringBoot环境下配置文件
1.总述
SpringBoot环境下常用的配置文件有两种,一种是properties属性文件,一种是yml文件。二者各有特点,语法也有很大区别,但是最终效果基本一致。
2.properties文件使用
文件名:application.properties
语法格式:
xxx.xxx.xxx=xxx
3.yml文件的使用
①yml简介
yml是YAML(YAML Ain’t Markup Language)语言的文件,以数据为中心,比json、xml等更适合做配置文件。
②yml语法
- 使用缩进表示层级关系
- 缩进时不允许使用Tab键,只允许使用空格。
- 缩进的空格数目不重要,只要相同层级的元素左侧对齐即可
- 大小写敏感
③YAML 支持的三种数据结构
- 对象:键值对的集合
- 数组:一组按次序排列的值
- 字面量:单个的、不可再分的值
spring:
application:
name: apple
server:
port: 8181
context-path: /banana
五、SpringBoot整合MyBatis
1.增加持久化层依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.5</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId