史上最全SpringBoot学习笔记-动力节点王鹤2021版springboot


SpringBoot

资料官方下载:动力节点官网

视频观看地址

https://www.bilibili.com/video/BV1XQ4y1m7ex

第一章 JavaConfig

为什么要使用 Spring Boot?

1. 因为Spring, SpringMVC 需要使用的大量的配置文件 (xml文件)

还需要配置各种对象,把使用的对象放入到spring容器中才能使用对象

需要了解其他框架配置规则。

2. SpringBoot 就相当于 不需要配置文件的Spring+SpringMVC。 常用的框架和第三方库都已经配置好了。

拿来就可以使用了。

3. SpringBoot开发效率高,使用方便多了

1.1 JavaConfig

JavaConfig: 使用java类作为xml配置文件的替代, 是配置spring容器的纯java的方式。 在这个java类这可以创建java对象,把对象放入spring容器中(注入到容器),

使用两个注解:

1)@Configuration : 放在一个类的上面,表示这个类是作为配置文件使用的。

2)@Bean:声明对象,把对象注入到容器中。

例子:

package com.bjpowernode.config;

import com.bjpowernode.vo.Student;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Configuration:表示当前类是作为配置文件使用的。 就是用来配置容器的
 *       位置:在类的上面
 *
 *  SpringConfig这个类就相当于beans.xml
 */
@Configuration
public class SpringConfig {

    /**
     * 创建方法,方法的返回值是对象。 在方法的上面加入@Bean
     * 方法的返回值对象就注入到容器中。
     *
     * @Bean: 把对象注入到spring容器中。 作用相当于
     *
     *     位置:方法的上面
     *
     *     说明:@Bean,不指定对象的名称,默认是方法名是 id
     *
     */
    @Bean
    public Student createStudent(){
        Student s1  = new Student();
        s1.setName("张三");
        s1.setAge(26);
        s1.setSex("男");
        return s1;
    }


    /***
     * 指定对象在容器中的名称(指定的id属性)
     * @Bean的name属性,指定对象的名称(id)
     */
    @Bean(name = "lisiStudent")
    public Student makeStudent(){
        Student s2  = new Student();
        s2.setName("李四");
        s2.setAge(22);
        s2.setSex("男");
        return s2;
    }
}

1.2 @ImporResource

@ImportResource 作用导入其他的xml配置文件, 等于 在xml

<import resources="其他配置文件"/>

例如:

@Configuration
@ImportResource(value ={ "classpath:applicationContext.xml","classpath:beans.xml"})
public class SpringConfig {
}

1.3 @PropertyResource

@PropertyResource: 读取properties属性配置文件。 使用属性配置文件可以实现外部化配置 ,

在程序代码之外提供数据。

步骤:

  1. 在resources目录下,创建properties文件, 使用k=v的格式提供数据
  2. 在PropertyResource 指定properties文件的位置
  3. 使用@Value(value="${key}")
@Configuration
@ImportResource(value ={ "classpath:applicationContext.xml","classpath:beans.xml"})
@PropertySource(value = "classpath:config.properties")
@ComponentScan(basePackages = "com.bjpowernode.vo")
public class SpringConfig {
}

第二 章 Spring Boot

2.1 介绍

SpringBoot是Spring中的一个成员, 可以简化Spring,SpringMVC的使用。 他的核心还是IOC容器。

特点:

  • Create stand-alone Spring applications

    创建spring应用

  • Embed Tomcat, Jetty or Undertow directly (no need to deploy WAR files)

    内嵌的tomcat, jetty , Undertow

  • Provide opinionated ‘starter’ dependencies to simplify your build configuration

    提供了starter起步依赖,简化应用的配置。

    比如使用MyBatis框架 , 需要在Spring项目中,配置MyBatis的对象 SqlSessionFactory , Dao的代理对象

    在SpringBoot项目中,在pom.xml里面, 加入一个 mybatis-spring-boot-starter依赖

  • Automatically configure Spring and 3rd party libraries whenever possible

    尽可能去配置spring和第三方库。叫做自动配置(就是把spring中的,第三方库中的对象都创建好,放到容器中, 开发人员可以直接使用)

  • Provide production-ready features such as metrics, health checks, and externalized configuration

    提供了健康检查, 统计,外部化配置

  • Absolutely no code generation and no requirement for XML configuration

    不用生成代码, 不用使用xml,做配置

2.2 创建Spring Boot项目

2.2.1 第一种方式, 使用Spring提供的初始化器, 就是向导创建SpringBoot应用

使用的地址: https://start.spring.io

SpringBoot项目的结构:
在这里插入图片描述

2.2.1 使用国内的地址

https://start.springboot.io
在这里插入图片描述

2.3 注解的使用

@SpringBootApplication

符合注解:由

  • @SpringBootConfiguration
  • @EnableAutoConfiguration
  • @ComponentScan

1. @SpringBootConfiguration

@Configuration
public @interface SpringBootConfiguration {
    @AliasFor(
        annotation = Configuration.class
    )
    boolean proxyBeanMethods() default true;
}

说明:使用了@SpringBootConfiguration注解标注的类,可以作为配置文件使用的, 可以使用Bean声明对象,注入到容器

2.@EnableAutoConfiguration

启用自动配置, 把java对象配置好,注入到spring容器中。例如可以把mybatis的对象创建好,放入到容器中

3.@ComponentScan

@ComponentScan 扫描器,找到注解,根据注解的功能创建对象,给属性赋值等等。 默认扫描的包: @ComponentScan所在的类所在的包和子包。

2.4 SpringBoot的配置文件

配置文件名称: application

扩展名有: properties( k=v) ; yml ( k: v)

使用application.properties, application.yml

例1:application.properties设置 端口和上下文

#设置端口号
server.port=8082
#设置访问应用上下文路径, contextpath
server.servlet.context-path=/myboot

例2: application.yml

server:
  port: 8083
  servlet:
    context-path: /myboot2

2.5 多环境配置

有开发环境, 测试环境, 上线的环境。

每个环境有不同的配置信息, 例如端口, 上下文件, 数据库url,用户名,密码等等

使用多环境配置文件,可以方便的切换不同的配置。

使用方式: 创建多个配置文件, 名称规则: application-环境名称.properties(yml)

创建开发环境的配置文件: application-dev.properties( application-dev.yml )

创建测试者使用的配置: application-test.properties

2.6 @ConfigurationProperties

@ConfigurationProperties: 把配置文件的数据映射为java对象。

属性:prefix 配置文件中的某些key的开头的内容。

@Component
@ConfigurationProperties(prefix = "school")
public class SchoolInfo {

    private String name;

    private String website;

    private String address;


    public String getName() {
        return name;
    }

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

    public String getWebsite() {
        return website;
    }

    public void setWebsite(String website) {
        this.website = website;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "SchoolInfo{" +
                "name='" + name + '\'' +
                ", website='" + website + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}

application.properties

#配置端口号
server.port=8082
#context-path
server.servlet.context-path=/myboot

#自定义key=value
school.name=动力节点
school.website=www.bjpower.com
school.address=北京的大兴区

site=www.bjpower.com

2.7 使用jsp

SpringBoot不推荐使用jsp ,而是使用模板技术代替jsp

使用jsp需要配置:

1) 加入一个处理jsp的依赖。 负责编译jsp文件


    org.apache.tomcat.embed
    tomcat-embed-jasper

2)如果需要使用servlet, jsp,jstl的功能


    javax.servlet
    jstl



    javax.servlet
    javax.servlet-api



javax.servlet.jsp
    javax.servlet.jsp-api
    2.3.1

3)创建一个存放jsp的目录,一般叫做webapp

? index.jsp

4)需要在pom.xml指定jsp文件编译后的存放目录。

META-INF/resources

5)创建Controller, 访问jsp

6)在application.propertis文件中配置视图解析器

2.8 使用容器

你想通过代码,从容器中获取对象。

通过SpringApplication.run(Application.class, args); 返回值获取容器。

public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) {
        return run(new Class[]{primarySource}, args);
}

ConfigurableApplicationContext : 接口,是ApplicationContext的子接口
public interface ConfigurableApplicationContext extends ApplicationContext

2.9 ComnandLineRunner 接口 , ApplcationRunner接口

这两个接口都 有一个run方法。 执行时间在容器对象创建好后, 自动执行run()方法。

可以完成自定义的在容器对象创建好的一些操作。

@FunctionalInterface
public interface CommandLineRunner {
    void run(String... args) throws Exception;
}

@FunctionalInterface
public interface ApplicationRunner {
    void run(ApplicationArguments args) throws Exception;
}

第三章 Web组件

讲三个内容: 拦截器, Servlet ,Filter

3.1 拦截器

拦截器是SpringMVC中一种对象,能拦截器对Controller的请求。

拦截器框架中有系统的拦截器, 还可以自定义拦截器。 实现对请求预先处理。

实现自定义拦截器:

1. 创建类实现SpringMVC框架的HandlerInterceptor接口

public interface HandlerInterceptor {
default boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
return true;
}

default void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
}

default void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
}
}

2. 需在SpringMVC的配置文件中,声明拦截器

xml

 
     
     class="拦截器类全限定名称"/>
 

SpringBoot中注册拦截器:

@Configuration
public class MyAppConfig implements WebMvcConfigurer {

    //添加拦截器对象, 注入到容器中
    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        //创建拦截器对象
        HandlerInterceptor interceptor = new LoginInterceptor();

        //指定拦截的请求uri地址
        String path []= {"/user/**"};
        //指定不拦截的地址
        String excludePath  [] = {"/user/login"};
        registry.addInterceptor(interceptor)
                .addPathPatterns(path)
                .excludePathPatterns(excludePath);

    }
}

3.2 Servlet

在SpringBoot框架中使用Servlet对象。

使用步骤:

  1. 创建Servlet类。 创建类继承HttpServlet
  2. 注册Servlet ,让框架能找到Servlet

例子:

1.创建自定义Servlet

//创建Servlet类
public class MyServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       //使用HttpServletResponse输出数据,应答结果
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out  = resp.getWriter();
        out.println("===执行的是Servlet==");
        out.flush();
        out.close();

    }
}
  1. 注册Servlet
@Configuration
public class WebApplictionConfig {

    //定义方法, 注册Servlet对象
    @Bean
    public ServletRegistrationBean servletRegistrationBean(){

        //public ServletRegistrationBean(T servlet, String... urlMappings)
        //第一个参数是 Servlet对象, 第二个是url地址

        //ServletRegistrationBean bean =
                //new ServletRegistrationBean( new MyServlet(),"/myservlet");


        ServletRegistrationBean bean = new ServletRegistrationBean();
        bean.setServlet( new MyServlet());
        bean.addUrlMappings("/login","/test"); // 


        return bean;
    }
}

软件系统不同组成部分衔接的约定。 用来提供应用程序与开发人员基于某软件或硬件得以访问的一组例程,而又无需访问源码,或理解内部工作机制的细节。

接口(API): 可以指访问servlet, controller的url, 调用其他程序的 函数

架构风格: api组织方式(样子)

就是一个传统的: http://localhost:9002/mytrans/addStudent?name=lisi&age=26

在地址上提供了 访问的资源名称addStudent, 在其后使用了get方式传递参数。

删除1的数据

需要的分页, 排序等参数,依然放在 url的后面, 例如

http://localhost:8080/myboot/students?page=1&pageSize=20

3) 一句话说明REST:

? 使用url表示资源 ,使用http动作操作资源。

4)注解

  • @PathVariable : 从url中获取数据
  • @GetMapping: 支持的get请求方式, 等同于 @RequestMapping( method=RequestMethod.GET)
  • @PostMapping: 支持post请求方式 ,等同于 @RequestMapping( method=RequestMethod.POST)
  • @PutMapping: 支持put请求方式, 等同于 @RequestMapping( method=RequestMethod.PUT)
  • @DeleteMapping: 支持delete请求方式, 等同于 @RequestMapping( method=RequestMethod.DELETE)
  • @RestController: 符合注解, 是@Controller 和@ResponseBody组合。

? 在类的上面使用@RestController , 表示当前类者的所有方法都加入了 @ResponseBody

5)Postman : 测试工具

使用Postman : 可以测试 get ,post , put ,delete 等请求

9.2 Thymeleaf属性

属性是放在html元素中的,就是html元素的属性,加入了th前缀。 属性的作用不变。 加入上th, 属性的值由模板引擎处理了。 在属性可以使用变量表达式

例如:

9.3 each

each循环, 可以循环List,Array

语法:

在一个html标签中,使用th:each

集合循环成员,循环的状态变量:两个名称都是自定义的。 “循环的状态变量”这个名称可以不定义,默认是"集合循环成员Stat"

each循环Map

在一个html标签中,使用th:each


集合循环成员,循环的状态变量:两个名称都是自定义的。 “循环的状态变量”这个名称可以不定义,默认是"集合循环成员Stat"
key:map集合中的key
value:map集合key对应的value值

9.4 th:if

“th:if” : 判断语句, 当条件为true, 显示html标签体内, 反之不显示 没有else语句

语法:
if=" 10 > 0 "> 显示文本内容

还有一个 th:unless 和 th:if相反的行为

语法:
当条件为false显示标签体内容

例子:if

if 使用

if="${sex=='m'}">性别是男

if="${isLogin}">已经登录系统

if="${age > 20}">年龄大于20

if="${name}">name是“”

if="${isOld}"> isOld是null

例子: unless

 

unless: 判断条件为false,显示标签体内容

性别是男的

登录系统

isOld是null

9.5 th:switch

th:switch 和 java中的swith一样的

语法:

switch="要比对的值">

case="值1"> 结果1

case="值2"> 结果2

case="*"> 默认结果

以上的case只有一个语句执行

9.6 th:inline

1. 内联text: 在html标签外,获取表达式的值

语法:

显示姓名是:[[${key}]]

内联 text, 使用内联表达式显示变量的值

我是[[${name}]],年龄是[[${age}]]

我是,年龄是

使用内联text

我是[[${name}]],性别是[[${sex}]]

2. 内联javascript

例子:
 <script type="text/javascript" th:inline="javascript">
         var myname = [[${name}]];
         var myage = [[${age}]];

         //alert("获取的模板中数据 "+ myname + ","+myage)

        function fun(){
            alert("单击事件,获取数据 "+ myname + ","+ [[${sex}]])
        }
    </script>

9.7 字面量

例子:

 

文本字面量: 使用单引号括起来的字符串

数据显示

数字字面量

if="${20>5}"> 20大于 5

boolean字面量

if="${isLogin == true}">用户已经登录系统

null字面量

if="${myuser != null}">有myuser数据

9.8 字符串连接

连接字符串有两种语法

1) 语法使用 单引号括起来字符串 , 使用 + 连接其他的 字符串或者表达式

  

数据显示

2)语法:使用双竖线, |字符串和表达式|

显示数据

例子:

    

字符串连接方式1:使用单引号括起来的字符串

数据显示



字符串连接方式2:|字符串和表达式|

9.9 运算符

  • 算术运 算: + , - - , * , / , %

  • 关系比较 : > , < , >= , <= ( gt , lt , ge , le )

  • 相等判断: == , != ( eq , ne )

    使用运算符

    年龄大于 10

    显示运算结果

    if="${myuser == null}">myuser是null

    if="${myuser eq null}">myuser是null

    if="${myuser ne null}">myuser不是null

    三元运算符: 表达式 ? true的结果 : false的结果 三元运算符可以嵌套

9.10 内置对象

文档地址:https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#web-context-namespaces-for-requestsession-attributes-etc.

#request 表示 HttpServletRequest

#session 表示 HttpSession对象

session 表示Map对象的, 是#session的简单表示方式, 用来获取session中指定的key的值

? #session.getAttribute(“loginname”) == session.loginname

这些是内置对象,可以在模板文件中直接使用。

例子:
 

内置对象#request,#session,session的使用

获取作用域中的数据



使用内置对象的方法

getRequestURL=
getRequestURI=
getQueryString=
getContextPath=
getServerName=
getServerPort=

9.11 内置工具类

内置工具类型: Thymeleaf自己的一些类,提供对string, date ,集合的一些处理方法

#dates: 处理日器的工具类

#numbers:处理数字的

#lists: 处理list集合的

日期类对象 #dates


内置工具类#numbers,操作数字的


内置工具类#strings,操作字符串

mystring 不是 空字符串


内置工具类#lists,操作list集合

if="${#lists.contains(mylist,'a')}">有成员a

if="!${#lists.isEmpty(mylist)}"> list 集合有多个成员


处理null

9.12 自定义模板

模板是内容复用, 定义一次,在其他的模板文件中多次使用。

模板使用:

1.定义模板

2.使用模板

模板定义语法:

th:fragment="模板自定义名称"

例如:

动力节点-java开发

www.

引用模板语法:

1) ~{templatename :: selector}
   templatename:  文件名称
   selector: 自定义模板名称
2)templatename :: selector
   templatename:  文件名称
   selector: 自定义模板名称

对于使用模板:有包含模板(th:include), 插入模板(th:insert)

第十章 总结

10.1 注解

Spring + SpringMVC + SpringBoot

创建对象的:

@Controller: 放在类的上面,创建控制器对象,注入到容器中 @RestController: 放在类的上面,创建控制器对象,注入到容器中。 作用:复合注解是@Controller , @ResponseBody, 使用这个注解类的,里面的控制器方法的返回值都是数据 @Service : 放在业务层的实现类上面,创建service对象,注入到容器 @Repository : 放在dao层的实现类上面,创建dao对象,放入到容器。 没有使用这个注解,是因为现在使用MyBatis框架,dao对象是MyBatis通过代理生成的。 不需要使用@Repository、 所以没有使用。 @Component: 放在类的上面,创建此类的对象,放入到容器中。 赋值的: @Value : 简单类型的赋值, 例如 在属性的上面使用@Value("李四") private String name 还可以使用@Value,获取配置文件者的数据(properties或yml)。 @Value("${server.port}") private Integer port @Autowired: 引用类型赋值自动注入的,支持byName, byType. 默认是byType 。 放在属性的上面,也可以放在构造方法的上面。 推荐是放在构造方法的上面 @Qualifer: 给引用类型赋值,使用byName方式。 @Autowird, @Qualifer都是Spring框架提供的。 @Resource : 来自jdk中的定义, javax.annotation。 实现引用类型的自动注入, 支持byName, byType. 默认是byName, 如果byName失败, 再使用byType注入。 在属性上面使用 其他: @Configuration : 放在类的上面,表示这是个配置类,相当于xml配置文件 @Bean:放在方法的上面, 把方法的返回值对象,注入到spring容器中。 @ImportResource : 加载其他的xml配置文件, 把文件中的对象注入到spring容器中 @PropertySource : 读取其他的properties属性配置文件 @ComponentScan: 扫描器 ,指定包名,扫描注解的 @ResponseBody: 放在方法的上面,表示方法的返回值是数据, 不是视图 @RequestBody : 把请求体中的数据,读取出来, 转为java对象使用。 @ControllerAdvice: 控制器增强, 放在类的上面, 表示此类提供了方法,可以对controller增强功能。 @ExceptionHandler : 处理异常的,放在方法的上面 @Transcational : 处理事务的, 放在service实现类的public方法上面, 表示此方法有事务 SpringBoot中使用的注解 @SpringBootApplication : 放在启动类上面, 包含了@SpringBootConfiguration @EnableAutoConfiguration, @ComponentScan MyBatis相关的注解 @Mapper : 放在类的上面 , 让MyBatis找到接口, 创建他的代理对象 @MapperScan :放在主类的上面 , 指定扫描的包, 把这个包中的所有接口都创建代理对象。 对象注入到容器中 @Param : 放在dao接口的方法的形参前面, 作为命名参数使用的。 Dubbo注解 @DubboService: 在提供者端使用的,暴露服务的, 放在接口的实现类上面 @DubboReference: 在消费者端使用的, 引用远程服务, 放在属性上面使用。 @EnableDubbo : 放在主类上面, 表示当前引用启用Dubbo功能。