快速搭建springboot项目

快速搭建springboot项目

1-首先使用idea创建一个空项目
2-在这个项目中创建一个maven工程
3-在java目录下guangda.springboot目录下面写一个测试类
在这里插入图片描述
4-启动main方法后,在浏览器输入http://localhost:8080/hello/show 如果访问“hello springboot 1” 则springboot项目创建成功。
5-优化main方法,独立出来,独立于所有的controller
6-在java目录下springboot目录下创建一个基类(引导类)
在这里插入图片描述

7-引导类再次优化 使用springBootApplication注解 (推荐使用,最简单)

@RestController
@EnableAutoConfiguration
@ComponentScan
@SpringBootApplication 经常使用
@SpringBootConfiguration
@Configuration 声明一个类为一个java配置类,相当于一个xml配置文件
@PropertySource 读取资源文件
@Bean 配置类上 把方法的返回值注入spring容器
@Value 注入参数
@ConfigurationProperties(prefix=“jdbc”) 声明一个类是一个属性读取类,读取application.properties
@EnableConfigurationProperties(属性读取类.class) 4种方法注入

@ConfigurationProperties 和@EnableConfigurationProperties 的关系
@EnableConfigurationProperties注解的作用是:使使用 @ConfigurationProperties 注解的类生效。
说明:
如果一个配置类只配置@ConfigurationProperties注解,而没有使用@Component,那么在IOC容器中是获取不到properties 配置文件转化的bean。说白了 @EnableConfigurationProperties 相当于把使用 @ConfigurationProperties 的类进行了一次注入。

spring的配置文件注入-读取资源文件(jdbc.properties) (存在代码冗余)
在这里插入图片描述
springBoot的配置文件注入-读取资源文件 (application.properties) (推荐使用) 如下图所示:
-springBoot所有的配置文件都在application.properties或者application.yml,默认只有一个配置文件 (启动springboot时自动读取)

在这里插入图片描述

第一种方法:通过autowired注入 (推荐使用)在这里插入图片描述
第二种方法:通过构造方法注入
在这里插入图片描述

springBoot实战

在这里插入图片描述

创建一个空项目,创建一个maven工程,引入依赖(parent和其他依赖)
1-整合Springmvc
在这里插入图片描述
2 -创建一个controller
在这里插入图片描述
3-创建配置文件application.yml (修改默认端口)
在这里插入图片描述

4-创建引导类
在这里插入图片描述
5-引入静态资源
在resources目录下创建static目录,在此目录下引入静态资源文件。
在浏览器地址栏输入http://localhost:8080/静态文件资源名就可以访问到相关资源文件。
6-添加拦截器
自定义一个拦截器实现类(MyInterceptor),实现HandlerInterceptor接口,重写其三个方法。
类上加一个@component注解 将类注入spring容器
在这里插入图片描述

然后配置拦截器 自定义一个java配置类,实现webMvcConfigurer接口

在这里插入图片描述
7-引入日志

在这里插入图片描述

8-整合数据库连接池(hikari(性能高),druid,c3p0(性能低))
在pom文件引入依赖
在这里插入图片描述
在application.yml内配置4大参数
spring.datasource.url=jdbc:mysql:///mybatis
spring.datasource.username=root
spring.datasource.password=root

spring.datasource.driverClassName=com.mysql.jdbc.Driver

spring.datasource.hikari.idle-timeout=60000
spring.datasource.hikari.maximum-pool-size=30
spring.datasource.hikari.minimum-idle=10

在这里插入图片描述
引入mybatis
在pom文件内添加mybatis启动器
在这里插入图片描述
在application.yml修改默认配置
在这里插入图片描述
创建pojo对象,创建UserMapper
在这里插入图片描述

在这里插入图片描述

引入通用mapper启动器
在这里插入图片描述
8-整合事物
创建UserService
在这里插入图片描述

修改UserController

在这里插入图片描述