SpringBoot3

1.SpringBoot概述:

  1. springboot介绍

    1. 基于SpringFramework一个快速整合和配置框架
    2. 快速的创建一个Spring工程
    3. 内置服务器软件
    4. 提供了多种场景启动器,快速引入场景需要的依赖
    5. 提供了写好的配置类,并且提供了按需加载
    6. 提供了生产级别的程序监控附带程序
    7. 没有xml文件配置
    8. 约定俗成,约定大于配置程序的很多参数赋予默认配置值
  2. springboot快速入门案例

    1. 主要步骤
      1. 创建maven工程
      2. 认springboot作为父工程
      3. 导入场景启动器
      4. 创建程序的主启动类
      5. 创建controller
      6. 启动程序即可

        b.创建maven工程

        c.添加依赖

<!--    所有springboot项目都必须继承自 spring-boot-starter-parent -->
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>3.0.5</version>
</parent>

<dependencies>
<!-- web开发的场景启动器 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

d.编写启动类

//是一个springboot的启动程序
@SpringBootApplication
public class Main {
    public static void main(String[] args) {

        //启动tomcat (创建ioc容器)
        SpringApplication.run(Main.class,args);
    }
}

e.添加controller

@RestController
@RequestMapping("boot")
public class HelloController {


    @GetMapping("hello")
    public String sayHello(){
        System.out.println("HelloController.sayHello");
        return "hello spring boot!!!";
    }
}
  1. 前期体验优势
    1. 简化整合: 对应场景启动器包含当前场景需要的所有依赖和配置类
    2. 简化配置(IoC): 自动加载配置类,将核心组件加入ioc容器
    3. 统一配置: 统一配置管理,集中方便配置
  2. 依赖管理机制理解
    1. 为什么导入starter-web(web场景启动器)所有相关依赖都导入进来?
    2. 为什么版本号都不用写?
      1. spring-boot-parent -> spring-boot-dependecies 声明完毕了
    3. 如何自定义版本号?
      1. 依赖的时候version
      2. 声明propertites属性覆盖
    4. 第三方依赖导入,父工程没有指定版本号如何处理?
      1. 自己声明version

二.SpringBoot统一配置管理:

  1. 统一配置管理机制
    1. 概述
      1. 约定配置参数写到固定的配置文件中
      2. 不需要指定加载,可以直接使用
    2. 配置文件内容分类
      1. 自定义配置,key随意定义,建议多层命名
      2. 其他启动器配置,key是固定的

Common Application Properties

    1. 配置文件规则
      1. 命名: application*
      2. 位置: resources文件夹下即可  **/application*.yml | yaml | properties
      3. 格式: properties | yaml , yml
  1. 属性配置文件和读取
    1. 缺点: 每次key全要自己写
    2. 优点: 清晰展示
  2. YAML配置文件和读取
    1. 优点: key可以靠缩进,进行多层简化
    2. 缺点:展示效果一般
  3. 批量配置文件读取
    1. 定义接收参数的组件
    2. 类上添加批量读取注解
    3. 确保属性名等于参数的最后一层key
@ConfigurationProperties(prefix = "my.data.user")
@Data
@Component
public class MyProperties {

    //@Value("${my.data.user.name}")
    private String name;

    //@Value("${my.data.user.age}")
    private int age;

}

my:
  data:
    user:
      age: 18
      name: xioamiong  

5.多环境profile配置和切换

  1. 声明分出去的配置
    1. 命名: application-{被激活的名}.yml | properties

     2. 主配置中激活分配置 

# 激活其他的配置文件
# 其他配置文件命名: application-{激活的文件名}.yaml
# 如果: 被激活文件和主配资参数重复,被激活优先!!!
spring:
  profiles:
    active: my,my1

三.SpringBoot自动配置原理

/**
 *  TODO: springBoot的启动类,都会添加@SpringBootApplication注解
 *       @SpringBootApplication
 *            作用1: @SpringBootConfiguration -> @Configuration -> 启动类就是配置类
 *            作用2: @ComponentScan(没有定义包) 如果不定义包,默认扫描配置类所在的包和后代包!
 *            作用3: @EnableAutoConfiguration 完成springboot自动化配置的!
 *
 *  1. 为什么我们自定义的组件类,放在启动类的相同包或者子包就会被扫描?
 *     答: @SpringBootApplication -> @ComponentScan -> 没有指定包,默认指定启动类所在的包或者后代包
 *     扩展: 如果[想修改默认]扫描的包,需要设置属性@SpringBootApplication(scanBasePackages="包") [了解]
 *
 *  2. ioc容器是在什么时候创建的?
 *     答: 启动类 -> main ->  SpringApplication.run(Main.class,args); -> ioc容器 | 启动tomcat
 *
 *  3. springboot是如何完成自动配置类加载? [面试题]
 *
 *     3.1 理解谁帮我们写的配置类?
 *         官方场景启动器需要的配置类: spring-boot
 *         第三方的场景启动需要的配置: 第三方自己定义

 *     3.2 配置类存储到什么位置了?
 *          所有的场景启动器都需要依赖一个[核心启动:boot工程启动的必备条件] spring-boot-starter
 *          spring-boot-starter / spring-boot-starter-autoconfigure -> 配置类
 *          真实包:  xxxxAutoConfiguration [142个配置类]  可能存在的组件数量 142 * 10 = 1420个
 *          清单内容: META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
 *                  org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration
 *                  org.springframework.boot.autoconfigure.aop.AopAutoConfiguration
 *                  org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration

 *     3.3 为什么不会直接加载所有配置类的组件?
 *         理解: 我们不需要所有的配置类,应该按需加载配置
 *         例如: 只有我导入了mq的包,才应该给我创建mq相关的组件,对应的配置类才应该生效!!
 *         解释: spring / ioc / 注解 / @Conditional [条件化注入] + @Bean [spring 4.0新特性]
 *               142个配置类,谁都会添加@Conditional注解!!!
 *               @ConditionalOnClass(Gson.class)
 *         实现: 按需加载
 *         问题: 不要瞎导入场景启动器!一旦导入了配置类就生效了! 配置类需要外部配置参数支撑,你没写配置参数!
 *
 *     3.4 springboot如何完成自动化配置加载(如何加载的这些配置类)?
 *          如何加载多个配置类:
 *             方案1: 创建ioc容器的时候,指定多个配置类  容器(配置类1.class,配置类2.class...)
 *             方案2: 在一个配置类上,@Import({其他配置类.class,其他配置类.class}),同时多个配置类生效
 *             方案3: 批量配置类导入, @Import(importSelector) -> 配置类的全限定符添加到对应的方法的数组中即可
 *          自动化配置方式: @SpringBootApplication -> @EnableAutoConfiguration -> @Import(142配置类) 不是
 *
 *          真正的自动导入:  @SpringBootApplication -> @EnableAutoConfiguration -> @Import(AutoConfigurationImportSelector.class)
 *                         AutoConfigurationImportSelector.class -> String[] selectImports ->
 *                         配置类的清单文件中,找到所有配置类的全限定符即可
 *                         [META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports]
 *
 *           @Conditional @Import + ImportSelector -> 清单内容
 *
 *  4. 场景启动的配置参数是如何读取的?
 *
 *        server.port = 8888 -> 端口 -> 配置类的参数 [固定读取server.port = key]
 *        配置类固定读取对应的key,只要修改就可以改变配置类的参数!!!
 *
 *        自动 == 固定
 *
 */

四.Spring自定义启动器

1.自定义启动器场景

1.封装通用功能模块:当你在多个项目中使用相同的功能模块时,可以考虑创建自定义启动器来封装这些通用功能。
通过自定义启动器,你可以将相关的依赖项、配置和自动化初始化代码打包在一起,使得在不同项目中使用该功能变得简单和一致。

2.解耦复杂的依赖关系:有时候,一个功能模块可能依赖于多个复杂的第三方库或组件。为了简化使用这种功能模块的流程,
你可以创建一个自定义启动器,将这些复杂的依赖项和配置进行封装和管理,而使用者只需引入自定义启动器,
而无需直接处理这些复杂的依赖关系。

2.自定义启动器需求

场景: 自动 加载指定的配置类

3.自定义启动器流程

        1.创建启动器项目
        2.引入启动器依赖
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>3.0.5</version>
</parent>

<groupId>com.atguigu</groupId>
<artifactId>springboot-hight-mybatis-starter-03</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
    <maven.compiler.source>17</maven.compiler.source>
    <maven.compiler.target>17</maven.compiler.target>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

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

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>
</dependencies>
3.准备组件类
@Data
public class SqlSessionFactoryBean {

    private String info;
}
4.准备配置类
@ComponentScan
@Configuration
public class MyBatisAutoConfiguration {

    @Autowired
    private MybatisProperties properties;

    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(){
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();

        System.out.println(properties.getAccount() + "||" + properties.getPassword());

        sqlSessionFactoryBean.setInfo(properties.getAccount() + "||" + properties.getPassword());
        return sqlSessionFactoryBean;
    }
}

5.编写自动配置

META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports 文件中编写好我们自动配置类的全类名即可

com.atguigu.config.MyBatisAutoConfiguration
6.使用自定义启动器

其他boot工程导入依赖即可

<dependency>
    <groupId>com.atguigu</groupId>
    <artifactId>springboot-hight-mybatis-starter-03</artifactId>
    <version>1.0-SNAPSHOT</version>
</dependency>

五.SpringBoot整合MyBatis

实现步骤:
  1. 导入对应的场景启动器和依赖(web,mybatis,jdbc,lombok)
  2. 定义mapper接口和mapperxml文件
  3. 启动的配置类上添加@MapperScanner("包")

mybatis必须得配置:
  spring:
    datasource:
      url: jdbc:mysql://localhost:3306/day01
      driver-class-name: com.mysql.cj.jdbc.Driver
      username: root
      password: root
      type: com.zaxxer.hikari.HikariDataSource

  # 可选的配置 别名 日志 xxx
  mybatis:
    type-aliases-package: com.atguigu.pojo
    mapper-locations: classpath:mappers/*.xml
    configuration:
      map-underscore-to-camel-case: true
      auto-mapping-behavior: full
      log-impl: org.apache.ibatis.logging.slf4j.Slf4jImpl


声明事务实现: @Transactional
  1. 导入事务的场景启动器 jdbc
  2. 直接使用注解  @Transactional

AOP的实现配置:
  1. 导入aop的场景启动器 aop
  2. 自己写切面即可

1.导入依赖

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>3.0.5</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>3.0.1</version>
    </dependency>

    <!-- 数据库相关配置启动器 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>

    <!-- 驱动类-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.28</version>
    </dependency>

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.28</version>
    </dependency>

</dependencies>

2.配置文件

application.properties

server:
  port: 8001


spring:
  datasource:
    url: jdbc:mysql://localhost:3306/数据库名
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: 123456
    type: com.zaxxer.hikari.HikariDataSource
  jackson:
    date-format: yyyy-MM-dd HH:mm:ss
    time-zone: GMT+8


#映射
mybatis:
 #是告诉 MyBatis 在类路径下的 /mappers/ 目录中查找所有以 .xml 结尾的文件,并将它们作为 SQL 映 
 射文件加载到 MyBatis 中。
  mapper-locations: classpath:/mappers/*.xml
  #类名映射 配置文件类名可小写
  type-aliases-package: com.atguigu.pojo
  configuration:
    #将数据库字段的下划线命名转换为驼峰命名规则
    map-underscore-to-camel-case: true
    #将数据库查询结果映射到 Java 对象
    auto-mapping-behavior: full
    log-impl: org.apache.ibatis.logging.slf4j.Slf4jImpl
#分页方言
pagehelper:
  helper-dialect: mysql

3.实体类准备

package com.atguigu.pojo;

@Data
public class User {
    private String account ;
    private String password ;
    private Integer id ;

4.Mapper接口准备

public interface UserMapper {

    List<User> queryAll();
}

5.MapperXML文件准备

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- namespace = 接口的全限定符 -->
<mapper namespace="com.atguigu.mapper.UserMapper">

    <select id="queryAll" resultType="user">
        select * from users
    </select>

</mapper>

6.启动类配置

@MapperScan("com.atguigu.mapper") //mapper接口扫描配置
@SpringBootApplication
public class MainApplication {

    public static void main(String[] args) {
        SpringApplication.run(MainApplication.class,args);
    }
}

六.SpringBoot整合SpringMVC

实现步骤:
 1. maven-> boot工程
 2. 导入场景启动器 (spring-boot-starter-web)
 3. 创建Controller实现接口 [json处理能力]

web场景启动器对应的配置:
  port:
  根路径:
  server:
    port: 8888
    servlet:
      context-path: /

静态资源问题:
   ssm -> mvc:default-servlet-handler (二秘书)
   外部访问的时候不需要写static文件夹名
   spring:
     web:
       resources:
         static-locations: classpath:/webapp/
   springboot -> 约定俗称 -> 约定大于配置 -> "classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"


拦截器配置:
   ssm -> 定义一个拦截器的实现类 -> xml -> <mvc:interceptors 标签
   boot -> 定义一个拦截器的实现类 -> 定义一个标准的配置类 -> 配置类中声明拦截器即可
   1. 定义拦截器
   2. 定义一个springmvc配置类 [提供了各个方向的配置方法] public class SpringMVCConfiguration  implements WebMvcConfigurer
   3. 重写添加拦截器的方法,完成添加即可
       @Autowired
       private MyInterceptor myInterceptor;

       @Override
       public void addInterceptors(InterceptorRegistry registry) {
             //拦截器 加入到 registry 参数中!
             registry.addInterceptor(myInterceptor).addPathPatterns("/**","/user/**")
                     .excludePathPatterns("/user/aaa")
                     .order(10);
       }

1.导入依赖

<?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>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.0.5</version>
    </parent>

    <groupId>com.atguigu</groupId>
    <artifactId>springboot-starter-springmvc-03</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <!--        web开发的场景启动器 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

</project>

2.启动配置类

@SpringBootApplication
public class MainApplication {

    public static void main(String[] args) {
        SpringApplication.run(MainApplication.class,args);
    }
}

3.实体类准备 

package com.atguigu.pojo;

@Data
public class User {
    private String username ;
    private String password ;
    private Integer age ;
    private String sex ;

4.controller编写

package com.atguigu.controller;

import com.atguigu.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/user")
public class UserController {

    @GetMapping("/getUser")
    @ResponseBody
    public User getUser(){
        
        User user = new User();
        user.setUsername("杨过");
        user.setPassword("123456");
        user.setAge(18);
        user.setSex("男");
        return user;
    }
}

5.web相关配置 

# web相关的配置
# https://docs.spring.io/spring-boot/docs/current/reference/html/application-properties.html#appendix.application-properties.server
server:
  # 端口号设置
  port: 80
  # 项目根路径
  servlet:
    context-path: /boot

6.静态资源处理 

# web相关的配置
# https://docs.spring.io/spring-boot/docs/current/reference/html/application-properties.html#appendix.application-properties.server
server:
  # 端口号设置
  port: 80
  # 项目根路径
  servlet:
    context-path: /boot
spring:
  web:
    resources:
      # 配置静态资源地址,如果设置,会覆盖默认值
      static-locations: classpath:/webapp

7.拦截器定义

        1.定义拦截器
package com.atguigu.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("MyInterceptor拦截器的preHandle方法执行....");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("MyInterceptor拦截器的postHandle方法执行....");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("MyInterceptor拦截器的afterCompletion方法执行....");
    }
}
2.声明拦截器
package com.atguigu.config;

import com.atguigu.interceptor.MyInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MvcConfig implements WebMvcConfigurer {

    @Autowired
    private MyInterceptor myInterceptor ;

    /**
     * /**  拦截当前目录及子目录下的所有路径 /user/**   /user/findAll  /user/order/findAll
     * /*   拦截当前目录下的以及子路径   /user/*     /user/findAll
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(myInterceptor).addPathPatterns("/**");
    }
}

七.SpringBoot 整合AOP和TX

  1.声明式事务

        1.导入依赖
 <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
        2.使用注解
@Transactional
public void update(){
    User user = new User();
    user.setId(1);
    user.setPassword("test2");
    user.setAccount("test2");
    userMapper.update(user);
}

2.Aop 的声明配置

        1.导入依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>
        2.aop切面配置
@Component
@Aspect
public class LogAdvice {

    @Before("execution(* com..service.*.*(..))")
    public void before(JoinPoint joinPoint){
        System.out.println("LogAdvice.before");
        System.out.println("joinPoint = " + joinPoint);
    }
}

九.项目打包运行

1.添加插件

<!--    SpringBoot应用打包插件-->
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
2.启动命令和参数 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值