SpringBoot学习

文章目录

SpringBoot

前言

1.什么是SpringBoot

博主认为就是一个集合了所有spring组件功能易于开发的一个工具箱,里面有我们想要的一切,便于我们的开发。
所以我们使用SpringBoot就是为了能快速创建出生产级别的Spring应用

2.SpringBoot优点

  • 创建独立Spring应用
  • 内嵌web服务器
  • 自动starter依赖,简化构建配置
  • 自动配置Spring以及第三方功能
  • 提供生产级别的监控、健康检查及外部化配置
  • 无代码生成、无需编写XML

基础学习中各种疑难问题或初见问题总结

注意:只有在容器中的组件,才会拥有SpringBoot提供的强大功能

1.@RestController

这个注解是@Controller、@ResponseBody的集合体

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {
    @AliasFor(
        annotation = Controller.class
    )
    String value() default "";
}

2.application.properties

改配置文件能修改集合在SpringBoot中的各种属性值
比如改个端口号

server.port=8888

具体能修改那种属性可以参考官方文档

3.Creating an Executable Jar

将项目的整个运行时环境打包成 "fat-jars"在maven中配置进去,这样部署服务器项目的时候就直接可以运行jar

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

将本项目打包成jar
在这里插入图片描述
在命令行窗口cd当前jar所在目录下执行以下命令

java -jar test01HelloWorld-1.0-SNAPSHOT.jar

在这里插入图片描述

此时服务器正常能访问
在这里插入图片描述

注意点:
• 取消掉cmd的快速编辑模式

4.自定义修改依赖版本

1、查看spring-boot-dependencies里面规定当前依赖的版本 用的 key。
2、在当前项目里面重写配置
    <properties>
        <mysql.version>5.1.43</mysql.version>
    </properties>

5.spring-boot-starter

spring场景启动器,里面有我们所有的依赖
当然如果不满足还可以引用第三方的启动器

6.主程序方法(项目名application.java)默认扫描范围

主程序主方法所在包及其子包都会扫描
修改方法:
• 想要改变扫描路径,@SpringBootApplication(scanBasePackages=“com.atguigu”)
• 或者@ComponentScan 指定扫描路径

7.@Conditional

@Conditional
条件装配:满足Conditional指定的条件,则进行组件注入

//这个就是有tom才装配进去
@ConditionalOnBean(name = "tom")
//这个就是除了tom都装配进去
@ConditionalOnMissingBean(name = "tom")

8.@ImportResource

当你还在用xml配置文件注入时,可以再要使用该对象的类上面使用本注解,写上xml文件的位置

@ImportResource("classpath:beans.xml")

9.@ConfigurationProperties

获取配置文件中bean对象的属性值,并注入进ioc,然后可创建对象

  1. @Component + @ConfigurationProperties
    在这里插入图片描述

  2. @EnableConfigurationProperties + @ConfigurationProperties
    在这里插入图片描述
    在这里插入图片描述

10.lombok

使用此依赖的目的是让pojo类的代码更加简洁,自动为我们生成setter和getter方法,以及tostring都可以用一个注解来解决
使用步骤:

  1. 引入依赖
		<dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
  1. 下载插件lombok,但好像这个插件已经是idea的默认插件了

效果瘦身前:

package com.lhjitem.boot.pojo;


public class Cat {
    private String name;

    @Override
    public String toString() {
        return "Cat{" +
                "name='" + name + '\'' +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Cat(String name) {
        this.name = name;
    }

    public Cat() {
    }
}

瘦身后:

package com.lhjitem.boot.pojo;

import lombok.AllArgsConstructor;//全参构造器
import lombok.Data;
import lombok.NoArgsConstructor;//无参构造器
import lombok.ToString;

@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class Cat {
    private String name;

}

进阶学习中各种疑难问题或初见问题总结

1.YAML(YML)

注意:YAML与properties的配置文件,优先级是先去properties,如果properties中没有相关的属性再去YAML中去找

1.1 什么是YAML

YAML是"YAML Ain’t a Markup Language"(YAML不是一种标记语言)的递归缩写。在开发的这种语言时,YAML 的意思其实是:“Yet Another Markup Language”(仍是一种标记语言),但为了强调这种语言以数据做为中心,而不是以标记语言为重点,而用反向缩略语重命名。

1.2 基本语法
  • key: value;kv之间有空格
  • 大小写敏感
  • 使用缩进表示层级关系
  • 缩进不允许使用tab,只允许空格
  • 缩进的空格数不重要,只要相同层级的元素左对齐即可
  • '#'表示注释
  • 字符串无需加引号,如果要加,''与""表示字符串内容 会被 转义/不转义
  • 数组可用[xxx,xxx]或 -xxx下一行对齐-xxx来表示
  • 集合可用{key:value}或 -xxx下一行对齐-xxx来表示
  • 当然如果数组或集合中存放的是对象的话对象属性的赋值也可用{key:value}或 -xxx下一行对齐-xxx来表示
    在这里插入图片描述
1.3 实例
  1. 创建一个perosn类
package com.lhjitem.boot.pojo;

import lombok.Data;
import lombok.ToString;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Data
@ToString
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
    private String userName;
    private Boolean boss;
    private Date birth;
    private Integer age;
    private Cat cat;
    private String[] interests;
    private List<String> animal;
    private Map<String, Object> score;
    private Set<Double> salarys;
    private Map<String, List<Cat>> allPets;
}

  1. 创建yaml配置文件,后缀为yml也行。配置文件内容
    在这里插入图片描述
person:
  userName: 李四
  boss: true
  brith: 2000/12/9
  age: 18
  cat:
    name: blue
    weight: 23.4
  interests: [ 篮球,游泳 ]
  animal:
    - jerry
    - mario
  score:
    english:
      first: 30
      second: 40
      third: 50
    math: [ 131,140,148 ]
    chinese: { first: 128,second: 136 }
    salarys: [ 3999,4999.98,5999.99 ]
    allCats:
      sick:
        - { name: tom }
        - { name: jerry,weight: 47 }
        - name: red
          weight: 67
      health: [ { name: mario,weight: 47 } ]

结果:
在这里插入图片描述

1.4 配置提示

自定义的类和配置文件绑定一般没有提示。

  <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
 <build>
 <!--将processor默认打包取消,防止每次启动太臃肿-->
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.springframework.boot</groupId>
                            <artifactId>spring-boot-configuration-processor</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

2.静态资源访问

2.1静态资源目录
  • 只要静态资源放在类路径下: called /static (or /public or /resources or /META-INF/resources
    访问 : 当前项目根路径/ + 静态资源名

  • 原理: 静态映射/**。
    请求进来,先去找Controller看能不能处理。不能处理的所有请求又都交给静态资源处理器。静态资源也找不到则响应404页面

  • 改变默认的静态资源路径及默认访问资源前缀

spring:
  mvc:
  # 默认无前缀,改变前缀如下
  # 改完访问资源就为:当前项目 + static-path-pattern + 静态资源名 = 静态资源文件夹下找
    static-path-pattern: /res/**

  resources:
  # 这个支持多个静态资源存放路径
    static-locations: [classpath:/haha/]
2.2 webjar

自动映射 /webjars/**
https://www.webjars.org/

        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>3.5.1</version>
        </dependency>

访问地址:http://localhost:8080/webjars/jquery/3.5.1/jquery.js 后面地址要按照依赖里面的包路径

3.欢迎页及自定义 Favicon(网页标签页左侧的小图标)

3.1 欢迎页支持

• 静态资源路径下 index.html
• 可以配置静态资源路径
• 但是不可以配置静态资源的访问前缀。否则导致 index.html不能被默认访问

spring:
#  mvc:
#    static-path-pattern: /res/**   这个会导致welcome page功能失效
  resources:
    static-locations: [classpath:/haha/]

• controller能处理/index

3.2 自定义 Favicon

favicon.ico 放在静态资源目录下即可。

spring:
#  mvc:
#    static-path-pattern: /res/**   这个会导致 Favicon 功能失效

4.REST风格

4.1 说明

在这里的rest风格只需要知道一点,要你需要表单提交不同方式时,你要在application中配置如下

spring:
  mvc:
    hiddenmethod:
      filter:
        enabled: true

因为默认rest风格的映射在springboot中是关闭的

4.2 postman

如PostMan直接发送Put、delete等方式请求,无需Filter。
就没有上面那些事了

4.3 不同请求的controller注解

其实就是帮你把默认属性值设置好了

	@DeleteMapping
    @PutMapping
    @GetMapping
    @PostMapping

5.请求参数与基本注解

5.1基本注解
@PathVariable:路径变量:“{xxx}”即能获取url中的各种参数的值

@RequestHeader:获取请求头信息

@ModelAttribute

@RequestParam:获取请求参数中的值,也是url的各种参数的值

@MatrixVariable(矩阵变量)
	//1、语法: 请求路径(href):/cars/sell;low=34;brand=byd,audi,yd
    //2、SpringBoot默认是禁用了矩阵变量的功能
    //      手动开启:原理。对于路径的处理。UrlPathHelper进行解析。
    //              removeSemicolonContent(移除分号内容)支持矩阵变量的
    //3、矩阵变量必须有url路径变量才能被解析
    @GetMapping("/cars/{path}")
    public Map carsSell(@MatrixVariable("low") Integer low,
                        @MatrixVariable("brand") List<String> brand,
                        @PathVariable("path") String path){
        Map<String,Object> map = new HashMap<>();

        map.put("low",low);
        map.put("brand",brand);
        map.put("path",path);
        return map;
    }

    // /boss/1;age=20/2;age=10,这种需要在MatrixVariable中再用一个属性来指定到底是1还是2


@CookieValue:获取cookie或cookie的值

@RequestBody:获取请求体中的数据,例如过个表单项提交的数据通过map获取

@RequestAttribute:获取请求域(map集合)中的值
5.2 自定义请求参数,封装POJO

如果对象之中引用对象,被引用的对象属性赋值使用级联进行赋值

测试负责类型:<hr/>
测试封装POJO:
<form action="/saveUser" method="post">
    姓名:<input name="userName" value="lisi"/><br>
    年龄:<input name="age" value="18"/><br>
    生日:<input name="birth" value="2000/6/27"/><br>
    宠物猫姓名:<input name="cat.name" value="blue"/><br>
    宠物猫年龄:<input name="cat.age" value="4"/><br>
    <!--使用自定义格式化来上传宠物猫属性-->
<!--    宠物猫:<input name="cat" value="blue,4"/>-->
    <input type="submit" value="保存"/>
</form>
</body>
</html>

控制器类

@RestController
public class ParameterTestController {
    /**
     * 数据绑定,无论是get还是post都可以和对象属性进行绑定
     * @param user
     * @return
     */
    @RequestMapping("/saveUser")
    public User saveUser(User user){

        return user;
    }
}

结果:
在这里插入图片描述

如果对象之中引用对象,被引用的对象属性赋值使用自定义的格式进行赋值
就比如:

<!--使用自定义格式化来上传宠物猫属性-->
宠物猫:<input name="cat" value="blue,4"/>

那么我们需要在自定义Web配置类中重写格式化方法

@Configuration//指明这是一个配置类
public class WebConfig {
    //WebMvcConfigurer定制SpringMVC的功能
    @Bean//加入容器中
    public WebMvcConfigurer webMvcConfigurer(){
        return new WebMvcConfigurer() {
            //自定义自定义对象上传字符串规则,不用联级
            @Override
            public void addFormatters(FormatterRegistry registry) {
                registry.addConverter(new Converter<String, Cat>() {

                    @Override
                    public Cat convert(String source) {
                        // 啊猫,3
                        if(!StringUtils.isEmpty(source)){
                            Cat cat = new Cat();
                            String[] split = source.split(",");
                            cat.setName(split[0]);
                            cat.setAge(Integer.parseInt(split[1]));
                            return cat;
                        }
                        return null;
                    }
                });
            }
        };
    }
}

结果:
在这里插入图片描述

6.SpringBoot默认错误信息处理机制

如果发生错误:

  • 对于浏览器端,会返回一个错误信息页面
  • 对于机器浏览器(例如postman),会返回一个json对象,里面有所有错误信息
6.1自定义错误信息展示页

当需要自定义错误信息展示页时,在templates文件夹下创建error,里面存放你需要的错误信息展示页
此时springboot会自动解析这个文件夹下的错误页面(5xx、4xx)然后展示
在这里插入图片描述

6.2 异常处理步骤
  1. 执行目标方法,目标方法运行期间有任何异常都会被catch、而且标志当前请求结束;并且用 dispatchException

  2. 进入视图解析流程(页面渲染?)
    processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);

  3. mv = processHandlerException;处理handler发生的异常,处理完成返回ModelAndView;
    • 1、遍历所有的 handlerExceptionResolvers,看谁能处理当前异常【HandlerExceptionResolver处理器异常解析器
    在这里插入图片描述

    • 2、系统默认的 异常解析器;
    在这里插入图片描述

    • 2.1 DefaultErrorAttributes先来处理异常。把异常信息保存到rrequest域,并且返回null;
    • 2.2 默认没有任何人能处理异常,所以异常会被抛出
    • 2.2.1 如果没有任何人能处理最终底层就会发送 /error 请求。会被底层的BasicErrorController处理
    • 2.2.2 解析错误视图;遍历所有的 ErrorViewResolver 看谁能解析。
    在这里插入图片描述

    • 2.2.3 默认的 DefaultErrorViewResolver ,作用是把响应状态码作为错误页的地址,error/500.html
    • 2.2.4 模板引擎最终响应这个页面 error/500.html

7.Web原生组件注入(Servlet、Filter、Listener)

7.1 使用Servlet API
  • @ServletComponentScan(basePackages = “com.atguigu.admin”) :指定原生Servlet组件都放在那里
  • @WebServlet(urlPatterns = “/my”):效果:直接响应,没有经过Spring的拦截器?
  • @WebFilter(urlPatterns={“/css/“,”/images/”})
  • @WebListener

推荐可以这种方式;
扩展:DispatchServlet 如何注册进来

  • 容器中自动配置了 DispatcherServlet 属性绑定到 WebMvcProperties;对应的配置文件配置项是 spring.mvc。
  • 通过 ServletRegistrationBean 把 DispatcherServlet 配置进来。
    • 默认映射的是 / 路径。

在这里插入图片描述

Tomcat-Servlet;
为什么配置好servlet以后/my不受springboot的拦截了:
因为多个Servlet都能处理到同一层路径,精确优选原则
A: /my/
B: /my/1

7.2 使用RegistrationBean

实例,前提是自己创建了三大组件的实现类

@Configuration
public class MyRegistConfig {

    @Bean
    public ServletRegistrationBean myServlet(){
        MyServlet myServlet = new MyServlet();

        return new ServletRegistrationBean(myServlet,"/my","/my02");
    }


    @Bean
    public FilterRegistrationBean myFilter(){

        MyFilter myFilter = new MyFilter();
//        return new FilterRegistrationBean(myFilter,myServlet());
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(myFilter);
        filterRegistrationBean.setUrlPatterns(Arrays.asList("/my","/css/*"));
        return filterRegistrationBean;
    }

    @Bean
    public ServletListenerRegistrationBean myListener(){
        MySwervletContextListener mySwervletContextListener = new MySwervletContextListener();
        return new ServletListenerRegistrationBean(mySwervletContextListener);
    }
}

8.嵌入式Servlet容器

8.1 springboot默认支持的服务器
  • 默认支持的webServer
    • Tomcat, Jetty, or Undertow
    • ServletWebServerApplicationContext 容器启动寻找ServletWebServerFactory 并引导创建服务器
    这是springboot默认支持的服务器
    在这里插入图片描述
  • 切换服务器
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
    <!--exclusions标签就是将xxx组件给移除掉-->
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <!--starter-xxxx就是啥服务器-->
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </exclusion>
    </exclusions>
</dependency>

9.定制化原理

9.1 定制化的常见方式
  • 修改配置文件;
  • xxxxxCustomizer;
  • 编写自定义的配置类 xxxConfiguration;+ @Bean替换、增加容器中默认组件;视图解析器
  • Web应用 编写一个配置类实现 WebMvcConfigurer 即可定制化web功能;+ @Bean给容器中再扩展一些组件
@Configuration
public class AdminWebConfig implements WebMvcConfigurer
  • @EnableWebMvc + WebMvcConfigurer —— @Bean 可以全面接管SpringMVC,所有规则全部自己重新配置; 实现定制和扩展功能
9.2 原理分析套路
  • 加粗项就是需要自己操心的步骤
    场景starter -> xxxxAutoConfiguration -> 导入xxx组件 -> 绑定xxxProperties --> 绑定配置文件项

10.数据库访问

10.1 数据库配置步骤
  1. 导入JDBC场景
 		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jdbc</artifactId>
        </dependency>

注意:导入的驱动版本要与本地数据库版本一致
这里假设我们导入mysql的数据库驱动

		<dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

默认springboot导入的版本为:
在这里插入图片描述
本机安装的版本为:
在这里插入图片描述
两种修改默认版本方法:

  • 直接依赖引入具体版本(maven的就近依赖原则)
		<dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.22</version>
        </dependency>
  • 重新声明版本(maven的属性的就近优先原则)
	<properties>
        <java.version>1.8</java.version>
        <mysql.version>8.0.22</mysql.version>
    </properties>
  1. 修改配置项
    注意:springboot默认底层配置好的连接池为:HikariDataSource
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/xxxx
    username: root
    password: 123456
    driver-class-name: com.mysql.jdbc.Driver
10.2 使用Druid连接池

在springboot中使用第三方的组件,配置方法都有两种:

  • 一是完全自定义
  • 二是找有没有xxx-starter

引入依赖

		<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.22</version>
        </dependency>
1. 自定义DataSourceConfig

基本都是参考druid的官方文档从xml中各项标签的配置转化为java代码的配置

@Configuration
@Configuration
public class MyDataSourceConfig {
    @Bean
    //从配置文件中获取数据源的相关配置
    @ConfigurationProperties("spring.datasource")
    public DataSource dataSource() throws SQLException {
        DruidDataSource druidDataSource = new DruidDataSource();
        //开启监控和防火墙功能
        druidDataSource.setFilters("stat,wall");
        return druidDataSource;
    }

    /**
     * 配置druid的监控页功能
     * @return
     */
    @Bean
    public ServletRegistrationBean statViewServlet(){
        StatViewServlet statViewServlet = new StatViewServlet();
        ServletRegistrationBean<StatViewServlet> registrationBean = new ServletRegistrationBean<>(statViewServlet, "/druid/*");
        //设置监控页的账号密码
        registrationBean.addInitParameter("loginUsername","root");
        registrationBean.addInitParameter("loginPassword","xxxx");
        return registrationBean;
    }

}

测试方法

@Controller
public class SqlController {
    @Autowired
    JdbcTemplate jdbcTemplate;

    @ResponseBody
    @GetMapping("/sql")
    public String SqlTest(){
        Long aLong = jdbcTemplate.queryForObject("select count(*) from account", long.class);
        return aLong.toString();
    }
}

监控页展示:
在这里插入图片描述

在这里插入图片描述

2.引入官方boot-starter配置

引入依赖

		<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.22</version>
        </dependency>

在application.yaml中编写配置,我们以前写的配置类就不需要了

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/mybatis_db?serverTimezone=GMT
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: 200627
    druid:
      filters: stat,wall	# 底层开启功能,stat(sql监控),wall(防火墙)
      aop-patterns: com.lhjitem.admin.*	#监控SpringBean
      stat-view-servlet:	# 配置监控页功能
        enabled: true
        login-username: root
        login-password: 200627
#        重置按钮
        resetEnable: false

      web-stat-filter:	# 监控web
        enabled: true
        url-pattern: /*
        exclusions: '*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*'

#     当你想单独配置filter里面的各种属性时
# 对上面filters里面的stat的详细配置
      filter:
        stat:
          slow-sql-millis: 1000
          log-slow-sql: true
        wall:
          enabled: true
          config:
            drop-table-allow: false

3.所遇到的问题
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/mybatis_db?serverTimezone=GMT&useSSL=false&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: 200627
  1. MySQL8.0及以上要在url中加入**?serverTimezone=GMT**,配置时区设置,不然报乱码错误
  2. driver-class-name中,不能用com.mysql.jdbc.Driver

11.整合Mybatis

11.1 配合Mapper.xml配置文件整合
  1. 引入mybatis依赖,导入mybatis官方starter
		<dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>
  1. 编写mapper接口。标注@Mapper注解
@Mapper
public interface AccountMapper {
    public Account getAccountById(Integer id);
}
  1. 编写sql映射文件并绑定mapper接口
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lhjitem.admin.mapper.AccountMapper">
    <select id="getAccountById" resultType="com.lhjitem.admin.pojo.Account">
        select * from account where id=#{id}
    </select>
</mapper>
  1. 在application.yaml中指定Mapper配置文件的位置,以及指定全局配置文件的信息 (建议;配置在mybatis.configuration)
#配置mybatis的规则
mybatis:
  config-location:  classpath:mybatis/mybatis-config.xml
  mapper-locations: classpath:mybatis/mapper/*.xml
  configuration:
    xx

注意:

  • 如果你写了mybatis的全局配置文件,那么就不能在yaml中配置configuration
    反过来同理,所以我们推荐在yaml中配置configuration
  • 还有就是如果数据库表名中属性有下划线,但在pojo对象中属性需要用到驼峰命名,这是需要在configuration配置驼峰命名(默认是关闭的)
11.2 配合纯注解使用

mapper

@Mapper
public interface Account2Mapper {
    @Select("select * from account2")
    public List<Account2> getAccounts();
}

service层

@Service
public class Account2Service {
    @Autowired
    Account2Mapper account2Mapper;

    public List<Account2> getAccts(){
        return account2Mapper.getAccounts();
    }
}

请求

@ResponseBody
    @GetMapping("/accts")
    public List<Account2> getAllAccount(){
        return account2Service.getAccts();
    }
11.3 注解与mapper.xml配合使用

遵循原则:

  • 简单sql语句用注解
  • 复杂sql语句在xml中配置

12.整合Mybatis-plus

12.1 说明

MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

12.2 步骤
  1. 导入依赖:
		<dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.2</version>
        </dependency>

注意导入这一个依赖以后,以下这两个依赖就不用导入了

		<dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jdbc</artifactId>
        </dependency>
  1. 编写pojo类(博主因为懒就用了以前的但是要做响应说明才行)
package com.lhjitem.admin.pojo;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor
@TableName("user2")
public class User {
    //TableField注解表明这两个属性是存在于测试表中的
    @TableField(exist = false)
    private String userName;
    @TableField(exist = false)
    private String password;

    //以下是数据库字段
    private Long id;
    private String name;
    private Integer age;
    private String email;
}
  1. 编写对应pojo类的mapper
//Mapper 继承该接口后,无需编写 mapper.xml 文件,即可获得CRUD功能
public interface UserMapper extends BaseMapper<User> {
}
  1. 编写测试类
@Test
    void testUserMapper(){
        User user = userMapper.selectById(1L);
        log.info("用户信息为:"+user);
    }
12.3 注意
  1. 从步骤来看根本就没有指定要查哪张表,也就是说mybatis底层是有默认规则的(例如实体类名为:User,会给你对应到数据库中的user表),但如果你数据库中没有按照默认规则创建对应的表名,此时就会报错。所以需要在你的pojo类中需要你用
@TableName("user2")

注解来制定是数据库中的那张表

  1. 在Mybatis-plus3.4.0以上版本时写逻辑删除的数据库字段时,不要直接用delete这些关键字,自己起一些相关的名字,不然会报错

13.Junit5单元测试

引入依赖

		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

注意:

  • SpringBoot 2.4 以上版本移除了默认对 Vintage 的依赖。如果需要兼容junit4需要自行引入(不能使用junit4的功能 @Test)
    JUnit 5’s Vintage Engine Removed from spring-boot-starter-test,如果需要继续兼容junit4需要自行引入vintage
<dependency>
    <groupId>org.junit.vintage</groupId>
    <artifactId>junit-vintage-engine</artifactId>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-core</artifactId>
        </exclusion>
    </exclusions>
</dependency>

测试类:

@SpringBootTest
class Boot05WebAdminApplicationTests {
	@Test
    void contextLoads() {
	}
}

以前spring的时候还需要@SpringBootTest + @RunWith(SpringTest.class)

13.1 常用注解
  • @Test :表示方法是测试方法。但是与JUnit4的@Test不同,他的职责非常单一不能声明任何属性,拓展的测试将会由Jupiter提供额外测试
  • @ParameterizedTest :表示方法是参数化测试,下方会有详细介绍
  • @RepeatedTest :表示方法可重复执行,下方会有详细介绍
  • @DisplayName :为测试类或者测试方法设置展示名称
  • @BeforeEach :表示在每个单元测试之前执行
  • @AfterEach :表示在每个单元测试之后执行,记得加上static
  • @BeforeAll :表示在所有单元测试之前执行,记得加上static
  • @AfterAll :表示在所有单元测试之后执行
  • @Tag :表示单元测试类别,类似于JUnit4中的@Categories
  • @Disabled :表示测试类或测试方法不执行,类似于JUnit4中的@Ignore
  • @Timeout :表示测试方法运行如果超过了指定时间将会返回错误
  • @ExtendWith :为测试类或测试方法提供扩展类引用
13.2 断言机制

断言(assertions)是测试方法中的核心部分,用来对测试需要满足的条件进行验证。这些断言方法都是 org.junit.jupiter.api.Assertions 的静态方法。
检查业务逻辑返回的数据是否合理。
所有的测试运行结束以后,会有一个详细的测试报告;
具体建议参考文档文档链接

14.指标监控

14.1 步骤
  • 引入场景
		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
  • 访问 http://localhost:8080/actuator/**
  • 暴露所有监控信息为HTTP
management:
  endpoints:
    enabled-by-default: true #暴露所有端点信息
    web:
      exposure:
        include: '*'  #以web方式暴露
  • 测试
    http://localhost:8080/actuator/beans
    http://localhost:8080/actuator/configprops
    http://localhost:8080/actuator/metrics
    http://localhost:8080/actuator/metrics/jvm.gc.pause
    http://localhost:8080/actuator/endpointName/detailPath

最常用的Endpoint
• Health:监控状况
• Metrics:运行时指标
• Loggers:日志记录

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值