SpringBoot入门到项目实战,带你快速上手springboot

2023-11-08

动力节点王鹤老师的SpringBoot入门系列课程,通俗易懂,基于SpringBoot2.4版本讲解。

从细节入手,每个事例先讲解pom.xml中的重要依赖,其次application配置文件,最后是代码实现。让你知其所以,逐步让掌握SpringBoot框架的自动配置,starter起步依赖等特性。

视频资源

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

SpringBoot

第一章 JavaConfig

  1. 为什么要使用 Spring Boot

    因为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>
     *
     *     位置:方法的上面
     *
     *     说明:@Bean,不指定对象的名称,默认是方法名是 id
     *
     */
    @Bean
    public Student createStudent(){
   
        Student s1  = new Student();
        s1.setName("张三");
        s1.setAge(26);
        s1.setSex("男");
        return s1;
    }


    /***
     * 指定对象在容器中的名称(指定<bean>的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项目的结构:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-dRfOaTEk-1645599534519)(D:\course\25-SpringBoot\笔记\images\image-20210115152427829.png)]

2.2.1 使用国内的地址

https://start.springboot.io

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-IN52drB7-1645599534520)(D:\course\25-SpringBoot\笔记\images\image-20210115155556662.png)]

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.bjpowernode.com
school.address=北京的大兴区

site=www.bjpowernode.com

2.7 使用jsp

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

使用jsp需要配置:

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

<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
</dependency>
  1. 如果需要使用servlet, jsp,jstl的功能
<dependency>
	<groupId>javax.servlet</groupId>
	<artifactId>jstl</artifactId>
</dependency>

<dependency>
	<groupId>javax.servlet</groupId>
	<artifactId>javax.servlet-api</artifactId>
</dependency>

<dependency>
<groupId>javax.servlet.jsp</groupId>
	<artifactId>javax.servlet.jsp-api</artifactId>
	<version>2.3.1</version>
</dependency>

  1. 创建一个存放jsp的目录,一般叫做webapp

​ index.jsp

  1. 需要在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
<mvc:interceptors>
 <mvc:interceptor>
 	<mvc:path="url" />
     <bean class="拦截器类全限定名称"/>
 </mvc:interceptor>
</mvc:interceptors>

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"); // <url-pattern>


        return bean;
    }
}

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

SpringBoot入门到项目实战,带你快速上手springboot 的相关文章

随机推荐

  • 学习日记——基于MDK的智慧物流案例开发(2020.2.19)

    准备阶段 开发板 小熊派开发板 提前组装 将 NB卡 NB35 A通信扩展板 E53 ST1GPS模块 IDE LiteOS Stiudio 小熊派的编译环境 平台 华为云账号 开通开发中心的权限 若使用软件开发服务进行应用开发 还需要开通
  • QT drawPixmap和drawImage处理图片模糊问题

    drawPixmap和drawImage显示图片时 如果图片存在缩放时 会出现模糊现象 例如将一个100x100 的图片显示到30x30的区域 这个时候就会出现模糊 如下 实际图片 这个问题就是大图显示成小图造成的像素失真 当我们在1080
  • ctf.show_web12

    f12提示 传参 cmd hightlight file index php 得到源码
  • 【抽五分钟】使用VuePress创建在线文档中心

    文章目录 安装初始化 核心配置 导航栏配置 侧边栏配置 静态资源配置 nginx部署 typora编写 安装初始化 全局安装 npm install g vuepress 创建目录 mkdir vurepress blog 项目初始化 cd
  • 使用 pair 做 unordered_map 的键值

    背景 标准库中 unordered map 是使用哈希表实现的 对于内置类型标准库通过 std hash 提供了哈希函数的实现 因此若采用非内置类型做键值 则需要程序员自己提供其哈希函数的实现 用 pair 做键值 自定义哈希函数 stru
  • Spring-Boot-Admin--快速学习--按应用实例添加标签--08

    代码地址 https gitee com DanShenGuiZu learnDemo tree master springboot admin learn 一 按应用实例添加标签 Tags 是我们区别同一应用的不同实例的方法 1 1 举例
  • 如何用电路区分 OC门与TTL

    这是两个概念 oc门是输出驱动方式 指集电极开路驱动 在电路中如果输出有一个电源到输出端的上拉电阻通常就是OC门 OC门只能灌电流 你说的TTL可能是指没注明的图腾拄驱动 即用不同极性的两个管子推拉驱动 不需要外接电源 高电平时可给负载提供
  • Vue第二篇:概念深度剖析

    参考链接 https www bilibili com video BV1oj411D7jk spm id from 333 788 recommend more video 0 vd source 3969f30b089463e19db0
  • 人生如一趟旅行

    http www putclub com html download life prose 2011 0311 27595 html Life is like a train ride We get on We ride We get of
  • HikariPool一直报连接不可用

    前言 一开始发现测试环境报错 原先配置6现在配置20依然还是很频繁的报错 想看下底层到底如何处理的导致这个问题 到底什么情况 排查 看了下日志连接数大量的空闲 看日志活跃的却是满的疑惑 2023 07 18 13 17 15 258 xxl
  • Java EnumMap putAll()方法具有什么功能呢?

    转自 Java EnumMap putAll 方法具有什么功能呢 下文笔者讲述EnumMap中putAll 方法的功能简介说明 如下所示 EnumMap中putAll 方法的功能 向map中批量添加一个map元素 EnumMap中putAl
  • MSBuild入门(续)

    MSBuild基本概念 续 在上一篇简单的介绍了下MSBuild中的四个基本块 每块介绍比较单薄 在这里对在大多数的项目模版生成的 proj文件中比较常见一些用法和概念做些补充 主要有一下几方面 MSBuild特殊字符 MSBuild保留的
  • 狄利克雷卷积 && 莫比乌斯反演

    狄利克雷卷积 莫比乌斯反演 狄利克雷卷积 数论函数及其运算 数论函数是指定义域是正整数 值域是一个数集的函数 加法 逐项相加 即 f h n f n h n 数乘 这个数和每一项都相乘 即 xf n x f n 狄利克雷卷积 定义两个数论函
  • Verilog 实现千兆网UDP协议 基于88E1111--数据发送

    Verilog 实现千兆网UDP协议 基于88E1111 数据发送 注 此版本没有添加ARP PING 等 未完待续 注 项目采用Verilog开发 基于Vivado编译器 UDP User Datagram Protocol 一种基本的
  • Ubuntu上面安装go语言

    一 下载go语言安装包 官方地址 https golang google cn dl 我这里下载的是go1 18 4 linux amd64 tar gz版本 二 把压缩包传入linux系统中 1 可以通过xshell连接Ubuntu系统
  • 关于海康,宇视,天地伟业摄像头调试

    最近在项目中需要读取摄像机的内容 现有的摄像机有海康威视 宇视 和天地伟业三家的摄像机 一开始 天地伟业和宇视都给了demo 即html和css代码 是可以读取视频流的 但是海康威视没有给demo 只是告诉我们可以通过vlc来读取视频流的内
  • 使用Inno Setup 打包成exe安装包+执行外部脚本文件

    有时候我们将软件需要做成类似下载后双击就能安装的程序 那么就需要使用打包工具进行打包 打包工具很多 有的简单 有的过程也比较复杂 如果有能力 自己可以写一个安装器 类似腾讯视频 优酷视频 哔哩哔哩的PC安装界面 这种就特别高大上 今天 主要
  • c++调用mxnet模型做预测

    python在深度学习领域很火 做实验用python很舒服 但是生产环境下可能还是需要c c 那么问题来了 mxnet训练出来的模型如何在c c 下调用 以下是一些填坑的经验分享一下 mxnet支持c c 调用模型 但目前不是全部的网络模型
  • 双向可控硅的四象限触发方式

    双向可控硅的四象限触发方式 双向可控硅是在普通可控硅的基础上发展而成的 它不仅能代替两只反极性并联的可控硅 而且仅需一个触发电路 是目前比较理想的交流开关器件 其英文名称TRIAC即三端双向交流开关之意 尽管从形式上可将双向可控硅看成两只普
  • SpringBoot入门到项目实战,带你快速上手springboot

    动力节点王鹤老师的SpringBoot入门系列课程 通俗易懂 基于SpringBoot2 4版本讲解 从细节入手 每个事例先讲解pom xml中的重要依赖 其次application配置文件 最后是代码实现 让你知其所以 逐步让掌握Spri