SpringBoot

本文详细介绍了SpringBoot与Mybatis的整合步骤,包括pom.xml配置、application.properties设置、Mapper接口使用、分页插件配置、单元测试以及SpringBoot的启动器和注解应用。此外,还探讨了配置文件的优先级、模板引擎Thymeleaf的使用和SpringBoot的异常处理机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Spring Boot

配置
-->pom.xml
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.yjd</groupId>
<artifactId>spring-boot1</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>

<!--
   spring boot相关技术管理的父工程
   不需要的依赖尤其是starter不要写在pom.xml文件中
   第三方技术的版本号必须有
-->
<parent>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-parent</artifactId>
 <version>2.5.2</version>
</parent>

<dependencies>
 <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
 </dependency>
 <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-thymeleaf</artifactId>
   <version>2.5.2</version>
 </dependency>
 <!--mybatis整合-->
 <!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
 <dependency>
   <groupId>org.mybatis.spring.boot</groupId>
   <artifactId>mybatis-spring-boot-starter</artifactId>
   <version>2.2.0</version>
 </dependency>
 <!--数据库连接,版本号可有可无-->
 <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
 <dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>8.0.23</version>
 </dependency>
 <!--分页插件,需要版本号-->
 <dependency>
   <groupId>com.github.pagehelper</groupId>
   <artifactId>pagehelper-spring-boot-starter</artifactId>
   <version>1.3.0</version>
 </dependency>
 <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-test -->
 <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
 </dependency>
 <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-jdbc</artifactId>
 </dependency>
 <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
 <dependency>
   <groupId>org.projectlombok</groupId>
   <artifactId>lombok</artifactId>
   <version>1.18.20</version>
   <scope>provided</scope>
 </dependency>
</dependencies>
</project>

-->application.properties
#视图解析器前后缀配置
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html

#数据库连接四元素
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springBoot?useUnicode=true&useSSL=false&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=mysql

#mapper映射文件配置
#如果mapper.xml映射文件和对应的接口处于同一个目录,且文件名称和对应的接口类名完全相同,可以省略配置,如下图
mybatis.mapper-locations=classpath:mapper/*Mapper.xml
#实体类别名配置
mybatis.type-aliases-package=com.yjd.pojo

-->程序入口
@SpringBootApplication
/**
 * mybatis提供的注解,用于扫描Mapper接口,用于生成动态代理
 * basePackages--扫描的包是哪个
*
 * */
/*@MapperScan(basePackages = {"com.yjd.mapper"})*/
public class DemoApplication {

 public static void main(String[] args) {

     ConfigurableApplicationContext run = SpringApplication.run(DemoApplication.class, args);
     String[] beanDefinitionNames = run.getBeanDefinitionNames();
     for (String bean : beanDefinitionNames
     ) {
         System.out.println(bean);
     }

 }
}
image-20210628202709351
技术点
-->需要注意的技术点
1、spring boot配置文件命名必须是application.properties/application.yml
2、如果mapper.xml映射文件和对应的接口处于同一个目录,且文件名称和对应的接口类名完全相同,可以省略配置
mybatis.mapper-locations=classpath:mappers/*Mapper.xml
3、mapper接口中需要使用@Mapper注解才能被扫描创建实例
4、mapper接口中可以为变量取别名
List<Student> selectByPage(@Param("start") int start, @Param("limit") int limit);
5、取model中对象属性
<!--后台出入键位student的student对象,取对象中值-->
<span th:text="${aa.id}"></span>
6、遍历list对象集合
<tr th:each="stu : ${list}" height="40px">
<th th:text="${stu.id}"></th>
<th th:text="${stu.name}"></th>
<th th:text="${stu.age}"></th>
<th th:text="${stu.gender}"></th>
<th th:text="${#dates.format(stu.birth,'yyyy-MM-dd HH:mm:ss')}"></th>
</tr>
7、前台接收日期格式数据
<th th:text="${#dates.format(stu.birth,'yyyy-MM-dd HH:mm:ss')}"></th>
8、遍历map集合中的list集合中的对象(rows为map的list集合的key)
<tr th:each="stu:${map.rows}">
<!--<tr th:each="stu:${map['rows']}">-->
<th th:text="${stu.id}"></th>
<th th:text="${stu.name}"></th>
<th th:text="${stu.age}"></th>
<th th:text="${stu.gender}"></th>
<th th:text="${#dates.format(stu.birth,'yyyy-MM-dd HH:mm:ss')}"></th>
</tr>
9、分页中的上下页
<tr height="40px">
<td colspan="2"><a th:href="@{/yjd/findByPage(page=${map.current}-1,rows=${map.rows})}" th:if="${map.current}>1">上一页</a></td>
<td colspan="3"><a th:href="@{/yjd/findByPage(page=${map.current}+1,rows=${map.rows})}" th:if="${map.current}<${map.totalPage}">下一页</a></td>
</tr>
Spring Boot启动器
1、自身启动器spring-boot-starter-xxx
2、第三方启动器xxx-spring-boot-starter(需加版本号)
简单使用
-->后端控制单元
@Controller
public class MyController {
 @RequestMapping(value = {"/","/index"})
 @ResponseBody
 public String  aa() {
     return "测试成功";
 }
}

-->后端启动类
@SpringBootApplication
public class DemoApplication {
 public static void main(String[] args) {
     ConfigurableApplicationContext run = SpringApplication.run(DemoApplication.class, args);
 }
}
property与filed区别
-->相同点
都是java类里的字段。
-->不同点
1、field一般是不暴露给外部的,只用作类或对象的内部数据储存使用;而property是需要暴露给外部的,用于控制类或对象的行为的参数;
2、field一般没有对应的set/get方法,但property必有对应的set/get方法,以便反射时获取或修改property的值。
3、field代表类中属性,如id;property代表set/get方法后的值,如getidProperty()中的idProperty
Spring Boot整合Mybatis
-->pom.xml
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.yjd</groupId>
<artifactId>spring-boot1</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>

<!--
   spring boot相关技术管理的父工程
   不需要的依赖尤其是starter不要写在pom.xml文件中
   第三方技术的版本号必须有
-->
<parent>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-parent</artifactId>
 <version>2.5.2</version>
</parent>

<dependencies>
 <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
 </dependency>
 <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-thymeleaf</artifactId>
   <version>2.5.2</version>
 </dependency>
 <!--mybatis整合-->
 <!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
 <dependency>
   <groupId>org.mybatis.spring.boot</groupId>
   <artifactId>mybatis-spring-boot-starter</artifactId>
   <version>2.2.0</version>
 </dependency>
 <!--数据库连接,版本号可有可无-->
 <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
 <dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>8.0.23</version>
 </dependency>
 <!--分页插件,需要版本号-->
 <dependency>
   <groupId>com.github.pagehelper</groupId>
   <artifactId>pagehelper-spring-boot-starter</artifactId>
   <version>1.3.0</version>
 </dependency>
 <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-test -->
 <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
 </dependency>
 <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-jdbc</artifactId>
 </dependency>
 <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
 <dependency>
   <groupId>org.projectlombok</groupId>
   <artifactId>lombok</artifactId>
   <version>1.18.20</version>
   <scope>provided</scope>
 </dependency>
</dependencies>
</project>

-->application.properties
#视图解析器前后缀配置
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html

#数据库连接四元素
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springBoot?useUnicode=true&useSSL=false&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=mysql

#mapper映射文件配置
#如果mapper.xml映射文件和对应的接口处于同一个目录,且文件名称和对应的接口类名完全相同,可以省略配置,如下图
mybatis.mapper-locations=classpath:mapper/*Mapper.xml
#实体类别名配置
mybatis.type-aliases-package=com.yjd.pojo

-->程序入口
@SpringBootApplication
/**
 * mybatis提供的注解,用于扫描Mapper接口,用于生成动态代理
 * basePackages--扫描的包是哪个
*
 * */
/*@MapperScan(basePackages = {"com.yjd.mapper"})*/
public class DemoApplication {

 public static void main(String[] args) {

     ConfigurableApplicationContext run = SpringApplication.run(DemoApplication.class, args);
     String[] beanDefinitionNames = run.getBeanDefinitionNames();
     for (String bean : beanDefinitionNames
     ) {
         System.out.println(bean);
     }

 }
}

Spring Boot注解
-->@SpringBootApplication
spring boot技术入口,扫描当前包和子孙包中所有spring注解
 
-->@Mapper
mapper接口注解,生成接口实例
实体类定义要素
实体类定义时,需要保证什么?
1、至少一个无参构造
2、getter和setter方法
3、toString方法重写
4、equals和hashcode方法重写
5、序列化接口
templates动态模板
-->不能使用ajax请求
-->templates文件夹下文件处于隐藏状态,需要通过控制单元跳转到对应页面
@Controller
public class MyController {

 @RequestMapping(value = {"/","/index"})
 public String  aa() {
     return "student/show";
 }

}

-->注意文件是否在文件夹下,若在,注意访问路径写法,如:return "student/addStudent";

Spring Boot整合Thymeleaf文件引擎
-->pom.xml配置
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>2.5.2</version>
</dependency>
 
-->属性
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
1、th:text="值"  -->将text中值当做文本值
<span th:text="${map.current}-1">文本值</span>
2、th:utext="值"  -->可以解析html语法
3、th:if="表达式"  -->if中表达式成立则当前标签生效显示,否则不显示
<a th:href="@{/yjd/findByPage(page=${map.current}-1,rows=${map.rows})}" th:if="${map.current}>1">
4、th:href="@{地址(参数名=参数值,参数名={作用域属性名})}"
<a th:href="@{/yjd/findByPage(page=${map.current}-1,rows=${map.rows})}" th:if="${map.current}>1">
5、th:src="@{地址(参数名=参数值,参数名={作用域属性名})}"
<img th:src="@{地址(参数名=参数值,参数名={作用域属性名})}"/>
6<tr th:each="stu:${map.list}">  -->迭代循环   循环变量名:${数组/集合}
<tr th:each="stu:${map.list}">
<!--<tr th:each="stu:${map['rows']}">-->
<th th:text="${stu.id}"></th>
<th th:text="${stu.name}"></th>
<th th:text="${stu.age}"></th>
<th th:text="${stu.gender}"></th>
<th th:text="${#dates.format(stu.birth,'yyyy-MM-dd HH:mm:ss')}"></th>
</tr>
7<input type="text" th:value=""/>  -->为文本框赋值

-->作用域传值
-->当作用域中值为对象或集合时,用法与EL表达式相同,如:<tr th:each="stu:${map.list}">
<!--request域取值-->
<span th:text="${aa}"></span>
<!--session域取值-->
<span th:text="${session.aa}"></span>
<!--model域中取值-->
<span th:text="${dd}"></span>
<!--请求转发取值-->
<span th:text="${ee}"></span>
<!--重定向取值-->
<span th:text="${param.ee}"></span>

-->接收日期格式
内置对象dates
处理日期格式化
format(日期对象,'格式化'<th th:text="${#dates.format(stu.birth,'yyyy-MM-dd HH:mm:ss')}"></th>
spring boot单元测试
-->单元测试需要在jar包下的test包下创建文件夹,测试类在新建文件夹下,不要叫Test类
单元测试必须依赖启动类型,从2.4.3版本开始,自动扫描classpath下所有自定义类型,找被@SpringBootApplication注解的类型,作为启动类型,初始化环境

@SpringBootTest -- 类上
@Test -- 方法上
可在测试类中注入想要的service和mapper,除了控制单元
-->@SpringBootTest
-->pom.xml继承parent,不用写版本
<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-test</artifactId>
 <scope>test</scope>
</dependency>
package com.yjd;

import com.yjd.pojo.Users;
import com.yjd.service.UsersService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

/**
 * @Author Ada
 * @Date 2021/6/30 19:17
*/
@SpringBootTest
public class TestAll {

 @Autowired
 private UsersService usersService;

 @Test
 public void test() {
     Users admin = usersService.login("admin");
     System.out.println(admin);
 }

}

老版本中需要加两个注解
-->@SpringBootTest(classes={启动类型.calss})
-->@RunWithSpringRunning.classpackage com.yjd;

import com.yjd.pojo.Users;
import com.yjd.service.UsersService;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * @Author Ada
 * @Date 2021/6/30 19:17
*/
@SpringBootTest(classes = {SecurityApp1.class})
@RunWith(SpringRunner.class)
public class TestAll {

 @Autowired
 private UsersService usersService;

 @Test
 public void test() {
     Users admin = usersService.login("admin");
     System.out.println(admin);
 }

}

-->pom.xml继承parent,不用写测试版本
<parent>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-parent</artifactId>
 <version>2.3.10.RELEASE</version>
</parent>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>


--测试单元
import com.yjd.DemoApplication;
import com.yjd.mapper.StudentMapper;
import com.yjd.service.StudentService;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

/**
 * @Author Ada
 * @Date 2021/6/28 21:43
*/
@SpringBootTest(classes = {DemoApplication.class})
public class test {

 @Autowired
 private StudentMapper studentMapper;

 @Autowired
 private StudentService studentService;

 @Test
 public void test() {
     int i = studentMapper.selectCount();
     System.out.println(i);
     int count = studentService.findCount();
     System.out.println(count);
 }

}
spring boot整合PageHelper
-->pom.xml配置
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
 
-->后台使用方式与springMVC时相同
@Override
public Map<String, Object> findByPage(int page, int rows) {
     PageHelper.startPage(page, rows);
     List<Student> students = studentMapper.selectByPage();
     PageInfo<Student> info = new PageInfo<>(students);
     List<Student> list = info.getList();
     long total = info.getTotal();
     int pageNum = info.getPageNum();
     int pages = info.getPages();
     int pageSize = info.getPageSize();
     int size = info.getSize();
     System.out.println(list);
     System.out.println("总数据量:" + total);
     System.out.println("当前页:" + pageNum);
     System.out.println("总页数:" + pages);
     System.out.println("每页数据量1:" + pageSize);
     System.out.println("每页数据量2:" + size);
     Map<String, Object> map = new HashMap<>();
     map.put("list", info.getList());
     map.put("total", info.getTotal());
     map.put("current", page);
     map.put("rows", rows);
     map.put("totalPage", pages);
     return map;
}
Spring Boot Bean管理方式
/**
 * @Componet 写在哪个类上表示把哪个类在项目启动时放入到Spring容器中。实例化该类对象
 * 名称是类名首字母小写,其他不变
 * 下面三个都是@Component的子注解。功能和@Component完全相同
 * 唯一区别:语义的区别。方便程序员阅读代码
 * @Service 专门放在service实现类上的
 * @Repository 专门放在数据库访问层实现类上的
 * @Configuration 配置类的,用于ApplicationContext初始化时配置的
*
*/

Configuration是框架提供的注解,相当于配置文件

-->实现
/**
 * 管理自定义bean对象的方式@Configuration作用于类,@Bean作用于方法上
 * 创建一个方法,返回值相当于bean中的class,方法名称相当于bean中的id属性
 * 参数列表,只提供ApplicationContext中有的变量,由spring自动注入,按照byName原则
 * @Bean(name={"别名"}/value={"别名"})-->name/value为bean定义别名,默认为方法名
 * 
*/
-->管理规则
1、当有多个bean对象交由Configuration配置类型管理,按照从上到下依次创建对象,有依赖关系时注意创建顺序
2、如果使用spring boot容器中的bean对象,做依赖关系处理,则可以使用以下方式
a、调用方法engine()
b、方法参数直接获取容器中的对象	public Car car(Engine engine)
c、使用@Autowired自动注入this.engine

//bean管理配置类
@Configuration
public class MyConfiguration {

 //实例化bean对象
 @Bean
 public Engine engine() {
     Engine engine = new Engine();
     engine.setId(1);
     engine.setType("w12");
     engine.setRemark("贵");
     return engine;
 }

 //bean对象中依赖其他bean对象,如Engine对象
 //a
 @Bean
 public Car car() {
     Car car = new Car();
     car.setId(1);
     car.setType("有字母的大众");
     car.setCreateTime(new Date());
     //注入由spring容器管理的bean对象
     car.setEngine(engine());
     return car;
 }

 //b
 @Autowired
 private Engine engine;
 @Bean
 public Car car() {
     Car car = new Car();
     car.setId(1);
     car.setType("有字母的大众");
     car.setCreateTime(new Date());
     car.setEngine(this.engine);
     //car.setEngine(engine);
     return car;
 }

     //c
 @Bean
 public Car car(Engine engine) {
     Car car = new Car();
     car.setId(1);
     car.setType("有字母的大众");
     car.setCreateTime(new Date());
     car.setEngine(engine);
     return car;
 }

}

-->启动类中使用
@SpringBootApplication
public class MyApp {

 public static void main(String[] args) {
     ConfigurableApplicationContext run = SpringApplication.run(MyApp.class);
     Object engine = run.getBean("engine");
     System.out.println(engine);
     Object car = run.getBean("car");
     System.out.println(car);

 }

}

Spring Boot支持的配置文件类型
-->***配置文件需要被标记为resources文件类型,配置文件才会有叶子图标并生效,但根目录下的配置文件布置如何搞??
支持配置文件类型properties、yml、yaml

优先读取properties,yml文件可读性更高
只能使用application命名配置文件
当properties与yml中都配置同一信息,优先读取properties中信息
当properties与yml中配置内容不同,以properties配置内容优先,yml配置内容做补充
 
-->YML配置进阶
springboot框架的配置文件有3种命名方式
bootstrap.properties|yml
application.properties|yml(默认配置文件)
application-profiles(任意名称).properties|yml
代表3种不同的读取顺序
bootstrap.properties|yml-->application.properties|yml-->激活的application-profiles.properties|yml
 
bootstrap.yml不是任意springboot都读取
需要特殊的依赖才能生效,如spring-cloud相关配置
代表spring容器正式初始化前,读取的配置文件
先读取bootstrap,初始化基本环境,再创建applicationContext
 
application-profiles.yml
application-dev.yml-->开发时使用的配置环境,数据库为本地,软件为自己电脑安装的
applicaiton-test.yml-->测试时使用的配置环境,有集中的数据库和其他软件环境,测试工程师
application-prod.yml-->上线时是使用的配置环境,使用正式服务器配置信息,运维工程师
激活:
spring:
	profiles:
		active: dev,test(从左向右)
               
profiles是springboot提供的多环境配置的核心,使用application.yml配置文件,增减spring.profeils.active配置,可以激活若干其他配置信息
         
-->springboot读取配置文件的绝对顺序是: 
->application.yml|properties 
-> 检查配置中是否有spring.profiles.active 
-> 如果没有则只读取当前配置文件,如果有,则读取对应的多环境配置文件。
->多个配置文件同时读取时,同名配置覆盖,不同名配置新增。后读取的配置,覆盖先读取的配置。
             
-->application.properties
#视图解析器前后缀配置
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
#数据库连接四元素
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springBoot?useUnicode=true&useSSL=false&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=mysql
#mapper映射文件配置
mybatis.mapper-locations=classpath:mapper/*Mapper.xml
#实体类别名配置
mybatis.type-aliases-package=com.yjd.pojo

-->application.yml
spring:
thymeleaf:
 prefix: classpath:/templates/
 suffix: .html
datasource:
 driver-class-name: com.mysql.cj.jdbc.Driver
 url: jdbc:mysql://localhost:3306/springBoot?useUnicode=true&useSSL=false&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
 username: root
 password: mysql

mybatis:
mapper-locations: classpath:mapper/*Mapper.xml
type-aliases-package: com.yjd.pojo

Spring Boot配置文件支持路径和优先级
1、可放在项目的根目录下,如:spring-boot1下
2、可放在项目根目录下创建的config文件夹下
3、可放在classpath(src/main/resources)/config文件夹下创建的config文件夹下
4、可放在classpath文件夹(resources)下
classpath等效于src/main/resources

-->配置文件加载顺序
忽略spring.profiles.active
1、项目根目录/config/application.properties
2、项目根目录/config/application.xml
3、项目根目录/application.properties
4、项目根目录/application.yml
5、classpath:/config/applicaiton.properties
6、classpath:/config/application.yml
7、classpath:/applicaiton.properties
8、classpath:/application.yml
9、根目录和根目录下config同等级
10、classpath和classpath下config同等级
11、最后加载profiles配置
application.yml文件自定义配置
-->application.yml文件中可以定义变量,测试单元中使用注解@Value获取并使用
-->application.yml定义变量
#自定义配置,为自定义属性提供默认值
#相当于在properties中配置了自定义变量,如test.str=xxx,测试单元中使用@Value("${test.str}")注解在属性上获取值
test:
str: '这是一个字符串'
int: 10
randInt: ${random.int}
randLong: ${random.long}
#配置中调用已配置的变量
str2: ${test.str}

-->测试单元中使用
@Controller
public class UsersController {
 @Value("${test.str}")
 private String str;
 @Value("${test.int}")
 private int i;
 @Value("${test.randInt}")
 private int randInt;
 @Value("${test.randLong}")
 private long randLong;
 @Value("${test.str2}")
 private String str2;

 @RequestMapping("/test")
 @ResponseBody
 public String test(){
     System.out.println("str = " + str);
     System.out.println("iw = " + i);
     System.out.println("randInt = " + randInt);
     System.out.println("randLong = " + randLong);
     System.out.println("str2 = " + str2);
     return "test";
 }
}
Spring Boot整合拦截器
过滤器考虑安全
拦截器考虑功能
 
-->配置拦截路径,一般定义在config文件夹下
@Configuration
public class MyInterceptor implements WebMvcConfigurer {

 @Autowired
 private LoginInterceptor loginInterceptor;

 @Override
 public void addInterceptors(InterceptorRegistry registry) {
     registry.addInterceptor(loginInterceptor).addPathPatterns("/**");
 }
}

-->创建拦截器,一般在interceptor文件夹下,被spring容器管理
@Component
public class LoginInterceptor implements HandlerInterceptor {

 @Override
 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
     System.out.println("前置拦截");
     return true;
 }

 @Override
 public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
     System.out.println("后置拦截");
 }

 @Override
 public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
     System.out.println("结束拦截");
 }
}
Spring Boot打包插件及部署
-->第一种方式,依赖parent 
-->pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.2</version>
</parent>
<build>
<plugins>
<!-- spring boot提供的打包插件
     主要使用其中的repackage功能。
     此功能,对maven的package功能做再加工。不需要特殊调用。
     直接使用maven的package功能,可以实现打包。
     简单使用的前提是,继承spring-boot-starter-parent
-->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

-->第二种方式,不依赖parent
<dependencyManagement>
<!-- 商业项目中,一般使用当前的管理策略。
     公司开发的是商业项目。至少不会把自己的项目挂载在开源组织spring之下。
-->
<dependencies>
  <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-dependencies</artifactId>
      <version>2.5.2</version>
      <type>pom</type> <!-- pom类型的项目 -->
      <scope>import</scope> <!-- 只在依赖的时候,使用其中的版本管理策略。 -->
  </dependency>
</dependencies>
</dependencyManagement>
 
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
  <execution>
    <id>repackage</id>
    <goals>
      <goal>repackage</goal>
    </goals>
  </execution>
</executions>
<configuration>
	<!--启动类全限定名-->
  <mainClass>com.yjd.MyApp</mainClass>
</configuration>
</plugin>
</plugins>
</build>

-->打包及启动过程
Lifecycle中clean->install到本地仓库jar包->cmd中运行jar包java -jar jar包名->网页正常访问即可

-->application.properties|yml中配置信息可在cmd运行jar包时启用
>java -jar D配置信息 jar包名
->java -jar Dserver.port=8080 jar包名
Spring Boot开发者工具
-->强烈不建议使用
springboot加载target字节码运行,不自动重新加载
tomcat不自动回收内存
<optional>打包时不把依赖加入jar包中
ctrl+shife+alt+?
不推荐使用,不利于分布式项目
Spring Boot异常处理
代码报错后,请求转发,转发地址为'/error',不能自己在控制单元中定义此映射,响应状态编码:
200成功
400请求错误
405请求方法错误
403无权限
500服务器错误
503服务器网关错误

-->异常处理时的查找顺序
-->精确匹配-->模糊匹配-->error.html
1、classpath/templates/error找状态码.html文件,可模糊匹配,如5xx.html
2、classpath/templates/error.html文件
3、降级处理fallback默认错误页面,spring容器提供
4、必须依赖thymeleaf
5、定义异常处理方式后,如异常处理可以被捕捉到,则不按照上述顺序查找,按照异常处理方法体中定义的方式处理

-->第一种处理异常方式,@ExceptionHandler,局部生效(当前类中程序异常可生效)
@Controller
public class MyController {

 @RequestMapping("/login")
 @ResponseBody
 public String login() {
     Random random = new Random();
     int i = random.nextInt(1000);
     if (i % 3 == 0) {
         return "无异常";
     } else if (i % 3 == 1) {
         throw new NullPointerException("空指针异常");
     } else {
         throw new IndexOutOfBoundsException("下标越界异常");
     }
 }
 
 //异常类型当做参数,可捕获该类型异常进行处理
 @ExceptionHandler
 @ResponseBody
 public String nullExce(NullPointerException exception) {
     return "空指针异常";
 }

}

-->第二种处理异常方式,@ControllerAdvice+@ExceptionHandler可捕捉全局符合参数类型的异常并处理
@ControllerAdvice
public class MyAdvice {

 @ExceptionHandler
 @ResponseBody
 public String exce(IndexOutOfBoundsException exception) {
     return "系统繁忙,请稍后重试";
 }

}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-eLrwhiXx-1654394066965)(C:\Users\纵横\AppData\Roaming\Typora\typora-user-images\image-20210629204125068.png)]

深入Spring Boot自动化装配原理
starter启动器,启动器运行时生效
 autoConfigure
 spring-boot-autoConfigure
 mybatis-spring-boot-autoConfigure
 
 matadata.json-->配置信息,默认值,有则写,没有不写
 
 spring.factories-->Auto Configure-->configuration类型环境装配,初始化创建对象		ctrl+n
 springfactoriesloader加载factories文件
 
 启动类型
 springfactoriesloader加载factories文件
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值