# springboot的快速应用 ## 1.springboot是什么 本阶段采用spring3.5.3版本 !\[image-20260514172330965\](D:\\课件\\07_springboot\\img\\image-20260514172330965.png) ## 2 传统方式构建spring应用 导入依赖麻烦: 1. 一个一个引入 2. jar包冲突或者版本冲突 !\[重新生成清晰图片\](D:\\课件\\07_springboot\\img\\1.png) 配置麻烦: !\[重新生成清晰图片\](D:\\课件\\07_springboot\\img\\2.png) !\[重新生成清晰图片 (1)\](D:\\课件\\07_springboot\\img\\3.png) ## 3 springboot特性 ### 3.1 起步依赖 本质就是maven坐标,整合完成了功能所需要的全部坐标 !\[image-20260514173133504\](D:\\课件\\07_springboot\\img\\image-20260514173133504.png) ### 3.2 自动配置 遵循约定大于配置的原则,在springboot程序启动后,一些bean对象会自动注入到ioc容器中,不需要手动声明------简化开发 !\[image-20260514173204521\](D:\\课件\\07_springboot\\img\\image-20260514173204521.png) !\[image-20260514173220357\](C:\\Users\\ThinkPad\\AppData\\Roaming\\Typora\\typora-user-images\\image-20260514173220357.png) ### 3.3 其他 #### 1 内嵌tomcat、jetty(意味着无需部署war包) 以前的项目需要打成war包,然后部署到tomcat或jetty中,springboot内嵌了服务器,比如tomcat,当springboot应用启动时,tomcat也会跟着启动,并且把当前项目的资源自动部署好,由于是内嵌的tomcat,我们以后只需要把springboot应用打成jar包,部署到线上后直接运行jar包即可开服 #### 2 外部配置 以前项目如果更改了配置文件后需要重新编译打包部署,而springboot项目只需要修改项目外面的配置文件,直接重启就行(不需编译打包部署) #### 3 不需要xml配置 以前项目有大量的xml配置文件, springboot项目只需要少量的配置 ## 4 springboot快速应用 需求:使用springboot开发一个web应用,浏览器访问/hello后,返回字符串 hello world! 1 创建maven工程 2 导入spring-boot-starter-web起步依赖 \`\`\`xml org.springframework.boot spring-boot-starter-web 3.5.14 \`\`\` 3.编写启动类 \`\`\`java @SpringBootApplication public class App { public static void main( String\[\] args ) { SpringApplication.run(App.class, args); } } \`\`\` 4.编写controller \`\`\`java @RestController @RequestMapping("/hello") public class TestController { @GetMapping("/word") public String hello() { return "hello world"; } } \`\`\` 5.启动访问测试 http://localhost:8080/hello/word ## 5.springboot的统一版本管理 5.1方式一 导入spring-boot-starter-parent 父工程 这样下面和springboot相关的依赖就不用在写 version版本号 \`\`\`xml spring-boot-starter-parent org.springframework.boot 3.5.14 org.springframework.boot spring-boot-starter-web junit junit 3.8.1 test \`\`\` 5.2方式二 使用dependencyManagement 来管理springboot的版本 这样下面和springboot相关的依赖就不用在写 version版本号 \`\`\`xml org.springframework.boot spring-boot-dependencies 3.5.14 pom import org.springframework.boot spring-boot-starter-web junit junit 3.8.1 test \`\`\` ## 6.编译和打包相关的插件配置 \`\`\`xml org.apache.maven.plugins maven-compiler-plugin 17 17 org.springframework.boot spring-boot-maven-plugin repackage \`\`\` # springboot的配置文件 作用: 1.便于管理,避免代码写死(硬编码) 2.支持外部配置,更改后不用重新打包,只需要重启服务即可 ## 1.springboot配置文件 ### 1.1properties 在resources下新建application.properties文件 \`\`\`properties #服务端口 server.port=8888 #服务路径 server.servlet.context-path=/admin \`\`\` !\[image-20260514181503520\](D:\\课件\\07_springboot\\img\\image-20260514181503520.png) ### 1.2yml/yaml 在resources下新建application.yml或者application.yaml文件 yml = yaml 都是一样的 \`\`\`yml server: port: 8080 servlet: context-path: /api \`\`\` ### 1.3自定义配置读/写 \`\`\`yml #自定义属性 student: name: "Student" age: 18 arr: - 刘亦菲 - 迪丽热巴 - 玛尔扎哈 - 玛卡巴卡 arr2: \[阿巴阿巴, 阿巴阿巴, 阿巴阿巴, 阿巴阿巴\] \`\`\` 读取配置文件的第一种方式 \`\`\`java @Component @ConfigurationProperties(prefix = "student") public class Student { private String name; private Integer age; private List arr; private List arr2; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public List getArr() { return arr; } public void setArr(List arr) { this.arr = arr; } public List getArr2() { return arr2; } public void setArr2(List arr2) { this.arr2 = arr2; } } \`\`\` 读取配置文件的第二种方式 \`\`\`java @RestController @RequestMapping("/hello") public class TestController { @Value("${student.name}") private String name; @Value("${student.age}") private Integer age; @GetMapping("/word") public String hello() { System.out.println(name); System.out.println(age); return "hello world"; } } \`\`\` ## 2.配置文件的优先级 如果三个文件在\*\*同一个目录\*\*下,Spring Boot 会先加载 \`application.properties\`。如果它没有定义某个配置项,则会去 \`application.yml\` 里寻找,最后才会使用 \`application.yaml\`。 但如果所有文件都定义了 \`server.port\`,那么最终生效的将是 \`.properties\` 文件中的端口号 ## 3.多环境配置 ### 3.1springboot多环境配置 为了方便指定生产、开服、测试环境(不用每次更换环境都要手动改配置),springboot可以通过配置来快速切换环境: 本质就是根据参数来指定读取哪一个配置文件 以下以yml举例: \`\`\`yml application.yml #基础配置 application-dev.yml #开发环境 application-test.yml #测试环境 application-prod.yml #生产环境 \`\`\` ### 3.2在application.yml中配置环境切换 \`\`\`yml spring: profiles: active: prod #这里指定多环境yml中的-后面的名字 \`\`\` ### 3.3多环境配置和spring.config.import配置区别 1 import目的是为了模块化配置。import配置的内容在基础yml是不会配置的; 多环境配置是为了在不同环境下配置不同的内容,比如服务ip、端口等,因此多个配置文件会配相似的内容 2 import无法支持参数启动,多环境可以支持参数启动 参数启动:基础yml可以不配置spring. profiles. active(就算配置了,优先级也\<启动参数配置) !\[image-20260518093553110\](D:\\课件\\07_springboot\\img\\image-20260518093553110.png) !\[image-20260518093618552\](D:\\课件\\07_springboot\\img\\image-20260518093618552.png) !\[image-20260518093630036\](D:\\课件\\07_springboot\\img\\image-20260518093630036.png) !\[image-20260518093638800\](D:\\课件\\07_springboot\\img\\image-20260518093638800.png) 如果是线上: java -jar xx.jar --spring.profiles.active=prod # Springboot集成Mybatis ## 1.导包 \`\`\`xml com.mysql mysql-connector-j org.mybatis.spring.boot mybatis-spring-boot-starter 3.0.3 \`\`\` 备注:mybatis要写版本是因为 MyBatis 并不属于 Spring Boot 官方模块 mysql驱动包不写版本因为 Spring Boot 已经通过 spring-boot-starter-parent 帮你管理了常见的依赖版本。(不用记) \`\`\`yml spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/springboot_demo?serverTimezone=Asia/Shanghai\&useUnicode=true\&characterEncoding=utf-8\&allowMultiQueries=true\&connectTimeout=30000\&socketTimeout=60000 username: root password: 123456 mybatis: #xml扫描路径 mapper-locations: classpath:mapper/\*\*/\*.xml #别名,不区分大小写 type-aliases-package: com.woniu.springboot_quick_start.entity configuration: #自动映射下划线转驼峰功能 map-underscore-to-camel-case: true \`\`\` ## 2.配置解释: localhost:数据库服务器地址,表示本地机器。 3306:MySQL 默认端口号。 springboot_demo:要连接的数据库名称。 在 ? 之后是连接参数,以键值对形式配置,多个参数用 \& 分隔: serverTimezone=Asia/Shanghai:设置服务器时区为上海时间,确保时间数据在时区上正确处理。 useUnicode=true:启用 Unicode 字符集支持,以便正确处理中文等字符。 characterEncoding=utf-8:设置连接使用的字符编码为 UTF-8。 allowMultiQueries=true:允许在一条 SQL 语句中执行多个查询,例如通过分号分隔多个 SQL。 connectTimeout=30000:连接超时时间为 30000 毫秒(即 30 秒),超过该时间未连接成功则抛出异常。 socketTimeout=60000:Socket 读取超时时间为 60000 毫秒(即 60 秒),超过该时间未收到数据则抛出异常 classpath: 表示从类路径(即 src/main/resources)下查找资源 mapper/ 表示在 resources 目录下的 mapper 文件夹中查找 \*\*/ 表示任意层级的子目录(递归查找) \*.xml 匹配所有以 .xml 结尾的文件 ## 3.xml xml正常情况是放在src/main/resources下的,如果需要放在src/main/java下 需要添加如下配置 \`\`\`xml 则需要额外在pom.xml中配置: src/main/java \*\*/\*.xml src/main/resources \`\`\` ## 4.搭建三层并测试 \`\`\`xml select \* from user where username=#{userName} and password=#{password} \`\`\` ### \*\*如果不想每个mapper接口都写@Mapper注解,可以直接在启动类配置@MapperScan\*\* \`\`\`java @SpringBootApplication @MapperScan("com.woniu.springbood.mapper") public class Application { public static void main(String\[\] args) { SpringApplication.run(Application.class, args); } } \`\`\` @MapperScan数组写法: @MapperScan({"com..."}) 或 @MapperScan(value={"com..."}) 或 @MapperScan(basePackages={"com..."}) Java 注解在语法设计上允许当属性是数组类型时,如果只传入一个元素,可以省略大括号 {},因此@MapperScan("com..")也是允许的 ## 5:LocalDateTime 和Date 如果是Date,则会在转换成json时因为时区问题相差8个小时(东八区),需要配置时区属性: \`\`\`java @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8") private Date updateTime; \`\`\` jdk1.8之后建议使用新版得到LocalDateTime # SpringbootTest ## 1.导包 \`\`\`xml org.springframework.boot spring-boot-starter-test test \`\`\` ## 2.测试 \`\`\`java @SpringBootTest @Transactional // 测试后自动回滚,保持数据库干净 public class UserServiceTest { @Autowired private UserService userService; @Autowired private UserMapper userMapper; @Test public void testCreateUser() { } } \`\`\` # 连接池配置 ## 1介绍 druid连接池 Druid 是阿里巴巴开源的一个高性能的数据库连接池组件,它不仅提供了连接池的基本功能,还内置了强大的监控和扩展能力。Druid 是目前 Java 生态中最常用的连接池之一,尤其在 Spring Boot 项目中被广泛使用。 Druid 在连接池中的作用: 1. 管理数据库连接的创建、复用、释放。 2. 避免频繁创建和销毁连接带来的性能损耗。 3. 提供连接池状态监控、SQL 监控、防火墙等附加功能。 springboot默认的连接池是HikariCP yml中需要配置 spring.datasource.type指定某个连接池 ## 2.依赖 \`\`\`xml com.alibaba druid-spring-boot-starter 1.2.19 \`\`\` ## 3.配置 \`\`\`yml spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/springboot_demo?serverTimezone=Asia/Shanghai\&useUnicode=true\&characterEncoding=utf-8\&allowMultiQueries=true\&connectTimeout=30000\&socketTimeout=60000 username: root password: 123456 # 指定数据源类型 type: com.alibaba.druid.pool.DruidDataSource druid: # 初始化连接池时建立的连接数 initial-size: 5 # 最小空闲连接数 min-idle: 5 # 最大连接数 max-active: 20 # 获取连接的最大等待时间(毫秒) max-wait: 60000 # 间隔多久才进行一次检测,检测需要关闭的空闲连接(毫秒) time-between-eviction-runs-millis: 60000 # 连接在池中保持空闲而不被驱逐的最小时间(毫秒) min-evictable-idle-time-millis: 300000 # 配置检测连接是否有效 validation-query: SELECT 1 FROM DUAL # 是否在空闲时测试连接有效性 test-while-idle: true # 是否在获取连接时测试连接有效性 test-when-idle: false \`\`\` # 其他 ## 1.封装统一返回类 \`\`\`java @Data @AllArgsConstructor @NoArgsConstructor public class Result { private int code;//描述状态 200 500 400 private String msg;//描述信息 成功 错误的相关信息 private T data; /\*\* \* 成功的 没有数据返回 \* @return \* @param \*/ public static Result success(){ return new Result\<\>(200,"成功",null); } /\*\* \* 成功的 有数据返回 \* @return \* @param \*/ public static Result success(T t){ return new Result\<\>(200,"成功",t); } /\*\* \* 失败 没有数据返回 \* @return \* @param \*/ public static Result error(String msg){ return new Result\<\>(500,msg,null); } /\*\* \* 失败 没有数据返回 \* @return \* @param \*/ public static Result error(String msg,T t){ return new Result\<\>(500,msg,t); } /\*\* \* 失败 \* @return \* @param \*/ public static Result error(){ return new Result\<\>(500,"操作失败",null); } /\*\* \* 失败 \* @return \* @param \*/ public static Result error(T t){ return new Result\<\>(500,"操作失败",t); } /\*\* \* 失败 \* @return \* @param \*/ public static Result error(int code,String msg){ return new Result\<\>(code,msg,null); } /\*\* \* 失败 \* @return \* @param \*/ public static Result error(int code,String msg,T t){ return new Result\<\>(code,msg,t); } } \`\`\` ## 2.封装pageResult 用于分页返回结果 \`\`\`java @Data @AllArgsConstructor @NoArgsConstructor public class PageResult { private Long total;//总条数 private List list;//分页集合 } \`\`\` ## 3.封装 PageParam \`\`\`java @Data public class PageParam { private Integer pageSize =1; private Integer pageNum =1; } \`\`\` ## 4.整合分页插件 \`\`\`xml com.github.pagehelper pagehelper-spring-boot-starter 2.1.0 org.apache.commons commons-lang3 \`\`\` 注意:pagehelper需要2.x版本才能兼容3.x的mybatis版本 \`\`\`yml pagehelper: #数据库方言,根据你使用的数据库选择 helper-dialect: mysql # 是否启用分页合理化,如 pageNum \< 1 时自动转为 1,如果pageNum\>pages则会查询最后一页 reasonable: true \`\`\`