Spring Boot 基础

SpringBoot

介绍

  • SpringBoot 相当于不需要配置文件的 Spring + Spring MVC

    • 常用的三方框架已经配置好,可以直接使用
    • SpringBoot 开发效率较高
  • SpringBoot 简化 Spring 和 SpringMVC 的使用

    • 例:Spring 中使用 Mybatis 需要配置 SelSessionFactory、Dao 代理对象
      • SpringBoot 中添加 mybatis-spring-boot-start 依赖即可,已经有默认配置可以直接使用
  • 核心还是 IoC 容器

  • 特点

    • 创建 Spring 应用
    • 内嵌 Tomcat,jetty,Undertow
    • 提供了 starter 起步依赖,简化应用配置
    • 自动配置:尽可能自动配置了 Spring 和 三方库
      • 第三方库中对象都创建好放到容器中
    • 提供健康检查、统计、外部化配置等功能
    • 无需生成代码,不用使用 xml 做配置

创建方式

  1. 使用 SpringBoot 的初始化器

    1. 以向导方式完成 SpringBoot 项目创建,使用方便
    • 必须联网创建
    1. 初始化器
    • 使用 默认地址 地址下载创建
    • 国外官方地址,容易失败
    1. 使用自定义地址
    1. 可以直接在浏览器使用地址创建项目
    • 创建完成后生成压缩包结构下载
  2. 使用 Maven 创建项目

    1. 不使用 模板创建
    2. 添加父依赖:spring-boot-starter-parent
    3. 自定义创建完整资源目录结构
    • 创建资源配置文件

在这里插入图片描述

POM.xml

  • 添加 web 启动依赖
  • thymeleaf 模板启动依赖
  • 开发工具:lombok、元信息配置
  • 启动器:SpringBoot 的启动场景
    • 比如:spring-boot-starter-web
      • 会自动导入所有 web 环境依赖
    • SpringBoot 将所有功能场景变成一个个启动器
44<?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 
         https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <!-- SpringBoot 父工程 -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.4</version>
        <relativePath/>
    </parent>
    <!-- 当前项目坐标 -->
    <groupId>com.example</groupId>
    <artifactId>demo2</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo2</name>
    <description>demo2</description>
    
    <!-- 项目属性配置 -->
    <properties>
        <java.version>1.8</java.version>
    </properties>
    
    <dependencies>
        <!-- thymeleaf 模板依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <!-- SpringBoot web 服务启动器 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- 自定义配置文件元信息:可以使框架识别自定义类信息 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <!-- lombok 依赖 -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <!-- 测试模块依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <!-- 打包插件 -->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project> 

任务

异步任务

  • @Async
    • 通知 Spring 异步方法
    • 注解在异步方法上
  • @EnableAsync
    • 开启异步注解
    • 注解在主启动类上
  • 后台进行业务处理但先返回浏览器一个结果
    • 异步执行:同时多线程执行任务

邮件任务

  • 添加启动项依赖:spring-boot-starter-mail
  • 配置 MainSenderAuutoConfig
配置文件
spring:
  mail:								# 邮箱配置
    host: smtp.qq.com				# 发送的主机服务器:qq
    username: 2217794007@qq.com		# 发件人账号
    password: 自己申请				 # QQ邮箱的授权码
    default-encoding: UTF-8			# 编码方式
    properties:						# 邮件类型配置
      mail:
        smtp:
          auth: true
          starttls:
            enable: true
            required: true
发送邮件
// 自动注入框架对象,可以完成发送邮件的功能
@Autowired
JavaMailSender sender;

/**
* 发送邮件:普通格式、html 格式
* @param multipart 是否允许多文件
* @param html 是否发送 html 格式
* @param subject 邮件标题
* @param text 邮件内容
* @param from 发送账号
* @param to 接收账号
*/
public void sendMessage(Boolean multipart, Boolean html, 
                        String subject, String text, 
                        String from, String to){
    MimeMessage mes = sender.createMimeMessage();
    try {
        // 帮助创建邮件、支持多文件、指定编码方式
        MimeMessageHelper helper = new MimeMessageHelper (mes, multipart, "UTF-8");
        helper.setSubject(subject);
        // 添加邮件内容、允许 html 格式
        helper.setText(text,html);
        // 添加附件
        helper.addAttachment("废物.jpg", new File("D:\\Pictures\\背.jpg"));
        helper.setTo(to);
        helper.setFrom(from);
        // 发送邮件
        sender.send(mes);
    } catch (MessagingException e) {
        e.printStackTrace();
    }
}

定时执行任务

  • 框架自带,无需添加依赖
  • 核心接口
    • TaskScheduler:任务调度
    • TaskExecutor:任务执行
  • 注解
    • @EnableScheduling:开启定时功能
    • @Sheduled:执行的时间
      • 添加表达式约定执行时间
        • cron:秒、分、时、日、月、周几
      • 例如:30 15 10 * * ?
        • 每天 10:15:30 执行

打包

war 包

  1. pom.xml 文件 配置内嵌 tomcat 对 jsp 的解析包

    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
    </dependency>
    
  2. 配置对 webapp 目录下 jsp 资源到指定目录的编译

    <build>
    <!-- 自定义打包后的文件名 -->
    <finalName>Spring_boot_demo</finalName>
    <!-- 编译指定的资源目录 -->
    <resources>
        <!-- 将 webapp目录下的资源文件编译到指定位置 -->
        <resource>
            <directory>src/main/webapp</directory>
            <targetPath>META-INF/resources</targetPath>
            <includes>
                <include>**/*.*</include>
            </includes>
        </resource>
        <!-- 编译 java 目录下的所有资源文件,例如 mapper.xml -->
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.*</include>
            </includes>
        </resource>
        <!-- 编译 resources 目录下的资源文件,包括 static 的静态资源 -->
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.*</include>
            </includes>
        </resource>
    </resources>
    </build>
    
    • 集成 mybatis 时配置 mapper.xml 文件的编译

    • 进行 src/main/resources 资源目录下的文件编译

    • 定义打包后的文件名

    • 指定打包方式为 war

      <packing>war</packing>
      
  3. 创建 webapp 资源目录,其中创建 jsp 页面;编写 controller 处理请求

    • 配置视图解析器:application.properties

      # 配置视图解析器
      spring.mvc.view.prefix=/
      spring.mvc.view.suffix=.jsp
      
  4. 主启动类继承 SpringBootServletInitializer

    • 将应用暴露出来
    • 可以使用外部 tomcat,此类相当于 web.xml 文件的替代
    • 使用嵌入式 Servlet 默认不支持 jsp
    //主启动类 继承 SpringBootServletInitializer
    @SpringBootApplication
    public class DemoApplication extends SpringBootServletInitializer {
    
        public static void main(String[] args) {
            SpringApplication.run(DemoApplication.class, args);
    
        }
    
        @Override
        protected SpringApplicationBuilder configure( SpringApplicationBuilder builder) {
            return builder.sources(DemoApplication.class);
        }
    }
    
  5. 使用 maven 将程序打包

    • 打包在 target 目录下有打包后的文件
  6. 将程序包放到 tomcat 发布目录之下(webapps)

    • 对照依赖的 tomcat 版本和外部 tomcat 版本

    • 启动 tomcat:端口号为本地 tomcat 端口号

      • 端口号由运行的 tomcat 决定
      • 会将程序包自动解压缩完成执行

jar 包

  1. 前三步跟打 war 包相同

    • 无需指定打包方式,默认 jar 包
  2. 不需要继承 SpringBootServletInitializer

    • 可以使用 SpringBoot 内嵌 tomcat 完成
  3. 配置插件

    • 指定 SpringBoot 的 maven-plugin 插件版本

      <plugin>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-maven-plugin</artifactId>
          <version>1.4.2.RELEASE</version>
      </plugin>
      
  4. 使用 maven 打包

    • 可以直接启动

      • 命令行窗口直接使用命令启动

        • 切换到 jar 包所在目录
        java -jar springboot_demo.jar
        
    • 可将命令封装到 Linux 的 shell 脚本(上线部署)

      • 写 shell 脚本:run.sh
      # #!/bin/sh 是对shell的声明,说明用的shell类型及其路径
      # #!/bin/sh 指此脚本使用 /bin/sh 解释执行
      # #!是特殊的表示符,后跟解释此脚本的shell的路径
      # 如果没有声明,则脚本将在默认的shell中执行
      # 默认shell由用户所在的系统定义为执行shell脚本的shell.
      
      # 表示使用 Linux shell 脚本
      #!/bin/sh 
      # springboot_demo.jar 和 run.sh 文件在同一目录
      java -jar springboot_demo.jar
      
      • 赋予权限 chmod 777 run.sh
  • 启动脚本:./run.sh

  • 独立启动,不依赖外部 tomcat

    • 端口号为内置 tomcat 端口号

区别

  • war 需要服务器启动
    • 占用资源较多
    • 能充分利用服务器,功能较强
  • jar 不需要服务器启动
    • 轻巧简单
      • 不需要过多操作
    • 使用内嵌 tomcat
      • 功能比不上独立服务器

注解总结

Spring + SpiringMVC + SpringBoot 部分注解

创建对象

@Controller
  • 放在 controller 类上面
  • 创建控制器对象注入到容器中
@RestController
  • 放在 controller 类上面,创建控制器对象注入到容器中
  • 作用:复合注解 @Controller @ResponseBody
    • 被注解的类中方法都是返回数据
@Service
  • 放在业务层接口的实现类上
  • 创建 service 对象注入到容器
@Repository
  • 放在 dao 层的实现类
  • 创建 dao 对象注入到容器
  • 当前无需使用,因为 MyBatis 框架中 dao 对象通过代理生成
    • 无需使用注解
@Component
  • 放到类上面创建类对象注入到容器中
    • 需要声明扫描器

赋值

@Value
  • 简单类型赋值
    • 例如 类属性
    • 基本类型 和 String 类型
@Autowired
  • 引用类型赋值
    • 支持 byName、byType;默认 byType
    • 可注解 setter 方法、属性、构造方法(推荐)
  • @qualifer:配合 @Autowired 使用
    • 给引用类型赋值使用 byName 方式
    • 指定赋值的对象(解决多个对象类型冲突问题)
  • Spring 框架 注解
@Resource
  • 引用类型赋值
  • 支持 byName、byType;默认 byName,若失败自动使用 byType
  • JDK 中的定义,javax.annotation

其他

@Configuration
  • 放在类上面作为配置类使用
    • 相当于 xml 文件
  • 配合 @Bean 使用
    • 注解在方法上将方法的放回值对象注入到 Spring 容器
@ImportResoure
  • 加载其他的配置文件,把文件中的 对象 注入到 Spring 容器中
@PropertyResource
  • 读取其他 外部 properties 配置文件
@ComponentScan
  • 扫描器,指定包名,扫描注解
@RequestBody
  • 将请求中的数据读取出来转为 Java 对象使用
    • 处理content-type不是默认的application/x-www-form-urlcoded编码的内容
      • 比如:application/json、application/xml等
      • 一般情况下来说常用其来处理application/json类型。
@ControllerAdvice
  • 控制器增强,定义在类上面
  • 表示此类提供方法可以对 controller 功能增强
  • 配合 @ExceptionHandler 注解实现全局异常处理
    • 注解在处理类中处理异常的方法上面
@Transcational
  • 事务处理,放在 service 实现类的 业务方法上表示此方法具有事务
@SpringBootApplication
  • 复合注解,放在启动类之上
    • @SpringBootConfiguration
      • 使用了 @Configuration 注解
      • 可以作为配置类、配置文件使用
        • 可使用 @Bean 声明对象注入到容器
    • @EnableAutoConfiguration
      • 启用自动配置
      • 将 Java 对象配置好注入到 Spring 容器中
        • 例如 自动创建 MyBatis 对象放到容器
    • @ComponentScan
      • 组件扫描器,找到注解创建对象
      • 默认扫描 @ComponentScan 所在类的包和子包
@Mapper
  • 放在 dao 接口,使 MyBatis 能找到接口创建 代理对象
  • @MaperScan 扫描 @Mapper 注解
    • 放在主类上
@Param
  • dao 接口方法形参前命名参数
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值