乐趣区

关于springboot:SpringBoot学习记录

SpringBoot 概述

SpringBoot 概念

SpringBoot 提供了一种疾速应用 Spring 的形式,基于约定优于配置的思维,能够让开发人员不用在配置与逻辑业务之间进行思维的切换,全身心的投入到逻辑业务的代码编写中,从而大大提高了开发的效率,肯定水平上缩短了我的项目周期。2014 年 4 月,Spring Boot 1.0.0 公布。Spring 的顶级我的项目之一(https://spring.io)。

Spring 毛病

配置繁琐

尽管 Spring 的组件代码是轻量级的,但它的配置却是重量级的。一开始 Spring 用 XML 配置,而且是很多 XML 配置。Spring 2.5 引入了基于注解的组件扫描,这打消了大量针对应用程序本身组件的显式 XML 配置。Spring 3.0 引入了基于 Java 的配置,这是一种类型平安的可重构配置形式,能够代替 XML。

所有这些配置都代表了开发时的损耗。因为在思考 Spring 个性配置和解决业务问题之间须要进行思维切换,所以编写配置挤占了编写利用程序逻辑的工夫。和所有框架一样,Spring 实用,但它要求的回报也不少。

依赖繁琐

我的项目的依赖治理也是一件耗时耗力的事件。在环境搭建时,须要剖析要导入哪些库的坐标,而且还须要剖析导入与之有依赖关系的其余库的坐标,一旦选错了依赖的版本,随之而来的不兼容问题就会重大妨碍我的项目的开发进度。

SpringBoot 性能

主动配置

SpringBoot 的主动配置是一个运行时 (更精确地说,是应用程序启动时) 的过程,思考了泛滥因素,才决定 Spring 配置应该用哪个,不该用哪个。该过程是 SpringBoot 主动实现的。

起步依赖

起步依赖实质上是一个 Maven 我的项目对象模型(Project Object Model,POM),定义了对其余库的传递依赖,这些货色加在一起即反对某项性能。简略的说:起步依赖就是将具备某种性能的坐标打包到一起,并提供一些默认的性能。

辅助性能

提供了一些大型项目中常见的非功能性个性,如嵌入式服务器、平安、指标,衰弱检测、内部配置等。

小结

SpringBoot 提供了一种疾速开发 Spring 我的项目的形式,而不是对 Spring 性能上的加强。

Spring 的毛病:

  • 配置繁琐
  • 依赖繁琐

SpringBoot 性能

  • 主动配置
  • 起步依赖
  • 辅助性能

SpringBoot 疾速入门

第一个 SpringBoot 程序

需要

搭建 SpringBoot 工程,定义 HelloController.hello()办法,返回”Hello SpringBoot!”。

思路

  1. 创立 Maven 我的项目
  2. 导入 SpringBoot 起步依赖
  3. 定义 Controller
  4. 编写疏导类
  5. 启动测试

实现

  1. 创立一个一般的 Java Maven 工程,最终的我的项目目录构造如图所示:

  2. 编写 pom.xml 配置文件,增加 SpringBoot 我的项目所需依赖

            <!--SpringBoot 的 web 我的项目起步配置依赖 -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
  3. 创立 HelloController 类,进行简略的业务代码书写

    package xyz.rtx3090.springboot.controller;
    
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    /**
     * @author BernardoLi
     * @version 1.0.0
     * @ClassName HelloController
     * @createTime 2021 年 09 月 11 日 08:22:00
     * @Description 第一个 springboot 程序
     */
    @RestController// 相当于 @[email protected]
    public class HelloController {@RequestMapping(value = "/hello")
        public String hello() {return "Hello World!";}
    }
  4. 创立 Application 启动类,用于启动 SpringBoot 我的项目

    package xyz.rtx3090.springboot;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    /**
     * @author BernardoLi
     * @version 1.0.0
     * @ClassName Application
     * @createTime 2021 年 09 月 11 日 08:25:00
     * @Description 疏导类:springboot 我的项目的入口
     */
    @SpringBootApplication
    public class Application {public static void main(String[] args){SpringApplication.run(Application.class,args);
        }
    
    }
  5. 运行 Application 类的 main 办法,启动 SpringBoot 我的项目,并在浏览器输出http://localhost:8080/hello

这样一个简略的 SpringBoot 我的项目曾经创立配置实现,比起 Spring 我的项目繁琐的配置要快捷不少。

但这还不是最快的,咱们还能够借助 idea 帮咱们进一步疾速创立 SpringBoot 我的项目!

第一个 SpringBoot 我的项目(更快版)

需要

应用 idea 提供的 springboot 模板创立我的项目,而不是采纳传统的 maven 我的项目,并实现和 第一个 SpringBoot 我的项目 案例一样的成果

思路

  1. 应用 idea 创立 SpringBoot 我的项目
  2. 创立编写 Controller 类
  3. 进入 Application 类,启动 SpringBoot 我的项目

实现

  1. 应用 idea 创立 SpringBoot 我的项目

  2. 我的项目最终目录构造,如图所示:

  3. 编写 HelloController 类,实现业务代码

    package xyz.rtx3090.springboot.controller;
    
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    /**
     * @author BernardoLi
     * @version 1.0.0
     * @ClassName HelloController
     * @createTime 2021 年 09 月 11 日 08:42:00
     * @Description 第一个 SpringBoot 程序(更快版)*/
    @RestController
    public class HelloController {@RequestMapping("/hello")
        public String hello() {return "hello SpringBoot!";}
    }
  4. 进去 Application 类,运行其 main 办法,启动 SpringBoot 我的项目

  5. 在浏览器输出http://localhost:8080/hello

这样一来,咱们就用很短的工夫实现了 SpringBoot 我的项目的部署和运行!

SpringBoot 起步依赖剖析

在 spring-boot-starter-parent 中定义了各种技术的版本信息,组合了一套最优搭配的技术版本。

在各种 starter 中,定义了实现该性能须要的坐标合集,其中大部分版本信息来自于父工程。

咱们的工程继承 parent,引入 starter 后,通过依赖传递,就能够简略不便取得须要的 jar 包,并且不会存在版本抵触等问题。

SpringBoot 配置剖析

配置文件分类

SpringBoot 是基于约定的,所以很多配置都有默认值,但如果想应用本人的配置替换默认配置的话,就能够应用 application.properties 或者 application.yml(application.yaml) 进行配置。

properties 文件

server.port=8080

yaml 文件

server: 
    port: 8080

小结

  • SpringBoot 提供了 2 种配置文件类型:properteisyml/yaml
  • 默认配置文件名称: application
  • 在同一级目录下优先级为: properties > yml > yaml

YAML 配置文件

概述

YAML 全称是 YAML Ain't Markup Language 。YAML 是一种直观的可能被电脑辨认的的数据数据序列化格局,并且容易被人类浏览,容易和脚本语言交互的,能够被反对 YAML 库的不同的编程语言程序导入,比方: C/C++, Ruby, Python, Java, Perl, C#, PHP 等。YML 文件是以数据为外围的,比传统的 xml 形式更加简洁。

YAML 文件的扩展名能够应用 .yml 或者.yaml

三种配置文件比照

  • properties格局

    server.port=8080 
    server.address=127.0.0.1
  • xml格局

    <server>
        <port>8080</port> 
      <address>127.0.0.1</address>
    </server>
  • yaml格局

    server:
        port: 8080
        address: 127.0.0.1

根本语法

  • 大小写敏感
  • 数据值前边必须有空格,作为分隔符
  • 应用缩进示意层级关系
  • 缩进时不容许应用 Tab 键,只容许应用空格(各个系统 Tab 对应的空格数目可能不同,导致档次凌乱)
  • 缩进的空格数目不重要,只有雷同层级的元素左侧对齐即可
  • \# 示意正文,从这个字符始终到行尾,都会被解析器疏忽

数据格式

  • 纯量(单个的、不可再分的值)

    # 纯量
    name: abc
    msg1: 'hello \n world'  #不会辨认转义字符,会原样输入
    msg2: "hello \n world"  #会辨认转义字符
  • 对象(键值对的汇合)

    # 对象
    person:
        name: ${name} #参数援用
        age: 22
    
    #对象行内写法
    human: {name: Bernardo,age: 22}
  • 数组(一组按秩序排列的值)

    # 数组
    address:
      - China
      - America
    
    #数组行内写法
    dizhi: [China,America]

参数援用

name: abc

person:
    name: ${name} #参数援用
    age: 22

读取配置文件

概述

Controller 类读取配置文件中咱们自定义的值,总共有三种形式:

  1. @Value
  2. Environment
  3. @ConfigurationProperties

@Value

作用 :注解@Value 将配置文件中的值单个逐个赋值给类中的被注解的属性

地位:类中的属性值上

毛病:不适宜配置文件值过多的状况

语法 @Value("${配置文件值名}")(须要留神:{} 中的值名须要与配置文件中的值名统一,而与类中的属性名无关联)

@Value("${配置文件值名}")
private String name;

演示

  1. 配置文件中的值

    name: abc
    
    person:
            name: Jason
        age: 22
        
    address:
      - China
      - America
  2. Controller 类读取配置文件的值

    @RestController
    public class HelloController {@Value("${name}")
        private String name;
    
        @Value("${person.name}")
        private String name2;
    
        @Value("${human.age}")
        private int age;
    
        @Value("${address[0]}")
        private String address1;
    
        @RequestMapping("/hello")
        public String hello() {
            return name + ";"
                    + name2 + ";"
                    + age + ";"
                    + address1 + ";";
        }
    }

Environment

作用 :类中通过引入 Environment 类型的属性值,而后让其属性值调用getProperty("配置文件值名") 来获取配置文件中的值

语法:(留神须要增加 @Autowired 注解)

@Autowired
private Environment env;

String age = env.getProperty("person.age")//person.age 为配置文件值名

演示

  1. 配置文件

    person:
        name: ${name} #参数援用
        age: 22
  2. 读取配置文件中的值

    @RestController
    public class HelloController {
    
          @Autowired
        private Environment env;
    
        @RequestMapping("/hello")
        public String hello() {return env.getProperty("address[1]")
        }
    }

@ConfigurationProperties(prefix = “ 配置文件值前缀 ”)

用法 :通过在实体类上增加@ConfigurationProperties(prefix = "配置文件值前缀") 注解,将配置文件的对象值注入的实体类中。而后只需在须要读取配置文件值的类中,引入实体类 类型的属性值,而后通过 set、get 办法即可读取到配置文件的值

留神:这个只能用于读取配置文件中对象类型的数据

  1. 配置文件

    person:
        name: Jason
        age: 22
        address:
          - China
          - America
  2. 实体类

    @Component
    @ConfigurationProperties(prefix = "person")
    public class Person {
        private String name;
        private int age;
        private String[] address;
    
        //setter and getter
    }
  3. 读取配置文件的数据

    @RestController
    public class HelloController {
    
        @Autowired
        private Person person;
    
        @RequestMapping("/hello")
        public String hello() {return person.getName() + ";"
                    + person.getAge() + ";"
                    + person.getAddress()[0] + ";"
                    + person.getAddress()[1];
        }
    }

多环境切换配置文件

概述

咱们在开发 Spring Boot 利用时,通常同一套程序会被装置到不同环境,比方: 开发、测试、生产等。其中数据库地址、服务器端口等等配置都不同,如果每次打包时,都要批改配置文件,那么十分麻烦。profile性能就是来进行动静配置切换的。

profile 配置多环境文件形式

  1. 多文件,命名辨别 的形式「举荐应用

    创立多个配置文件,每个配置文件后用 - 关键字 的形式来辨别。

    留神:必须是用 - 来分隔关键字,关键字能够自定义,但最好见名知意。关键字是前面激活特定配置文件的要害!

    每个不同关键字的配置文件,咱们都能够配置齐全不同的配置,用于各种环境切换应用。

    这种多环境文件配置的形式,profileyaml 类型的配置文件都同样实用!

    最简略的激活形式,就是间接在总配置文件中增加spring.profiles.active= 关键字,即可激活对应的配置文件。

  2. 单文件,---分隔 的形式

    只须要创立一个繁多的文件,而后应用 --- 来进行分隔多种不同环境的配置(详情看上面代码)。

    只实用于 yaml 类的配置文件。

    ---
    server:
      port: 8080
    
    spring:
      config:
        activate:
          on-profile: dev
    ---
    server:
      port: 8081
    
    spring:
      config:
        activate:
          on-profile: test
    ---
    server:
      port: 8082
    
    spring:
      profiles:
        active: pro #激活
    ---

多环境配置文件的激活形式

  1. 在配置文件中激活

    间接在配置文件中退出spring.profiles.active= 关键字,即可激活对应的配置文件

  2. 命令行激活

    命令行激活,是在命令行运行对应 jar 时,采纳的一种切换配置文件的形式。

    语法:java -jar 我的项目 jar 包 --spring.profiles.active= 关键字

    益处:不须要批改配置文件,间接在 jar 运行前就能够手动切换 jar 包,快捷不便

  3. 在 JVM 虚拟机中激活

    在我的项目 SpringBoot 配置中的 VM options中设置-Dspring.profiles.active= 关键字,也能够激活对应的配置文件

外部配置文件加载程序

优先级从高到低顺次为:

  1. 总我的项目下的 /config 目录下的 application.properties 配置文件
  2. 总我的项目下的 application.properties 配置文件
  3. 以后我的项目下 /config 目录下的 application.properties 配置文件
  4. 以后我的项目下的 application.properties 配置文件

高优先级的配置文件失效,并不意味着低优先级的配置文件可齐全没用了。高优先级配置文件只是会笼罩掉低优先级配置文件的与其反复的配置内容,除此之外并不会影响低配置文件其余与其不反复的配置内容的失效!

如果把以后我的项目打成 Jar 包,本我的项目如果不是总我的项目的话,那么总我的项目外面的配置文件并不会被打入 Jar 包,也就不会失效!

上面是我的项目理论多个配置文件,优先级图解:

内部配置文件加载程序

咱们除了能够在我的项目打包的 Jar 包中寄存配置文件,咱们还能够在我的项目的打包的 Jar 包寄存配置文件。

优先级从高到低顺次为:

  1. Jar 包同级目录下的 /config 目录下的配置文件
  2. Jar 包同级目录下的配置文件

SpringBoot 整合其余框架

SpringBoot 整合 Spring+SpringMVC

这一节,咱们在 SpringBoot 疾速入门 中,创立演示的 第一个 springboot 程序 就是 springboot 整合 Spring+SpringBoot 框架的案例。具体会看上节!

SpringBoot 整合 Junit

需要

应用 SpringBoot 整合 Junit 测试框架,并实现测试操作

思路

  1. 搭建 SpringBoot 工程
  2. 引入 starter-test 起步依赖(主动的)
  3. 编写被测试类
  4. 编写测试类,增加测试注解@SpringBootTest(classes = 启动类.class)

实现

  1. 查看创立的 springboot 我的项目 pom 文件中是否有 spring-boot-starter-test 依赖,没有须要本人手动增加

            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
  2. 编写被测试 service 类

    @Service
    public class UserService {public void add() {System.out.println("add...");
        }
    }
  3. 编写测试类,注解的参数为正式启动类.class

    @SpringBootTest(classes = Application.class)// 留神这里
    public class UserServiceTest {
    
        @Autowired
        private UserService userService;
    
       @Test
        public void testAdd() {userService.add();
        }
    }

SpringBoot 整合 Redis

需要

应用 SpringBoot 整合 Redis 数据库,并实现 Redis 数据库操作

思路

  1. 搭建 SpringBoot 工程(勾选NoSQL->Spring Data Redis (Access+Driver)
  2. 引入 redis 起步依赖(如果上一步勾选了,则不须要手动引入依赖了)
  3. 在配置文件中,配置 redis 的 ip 端口等信息(不配置的话,默认为 localhost:6379)
  4. 注入 RedisTemplate 模板
  5. 编写测试方法,测试

实现

  1. 搭建 SpringBoot 工程(勾选NoSQL->Spring Data Redis (Access+Driver)
  2. 编写测试类ApplicationTests

    package xyz.rtx3090.springboot;
    
    import org.junit.jupiter.api.Test;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.data.redis.core.RedisTemplate;
    
    @SpringBootTest
    public class ApplicationTests {
    
        @Autowired
        private RedisTemplate redisTemplate;
    
        @Test
        public void testSet() {
            // 存入数据
            redisTemplate.boundValueOps("name").set("Jason");
        }
    
        @Test
        public void testGet() {
            // 获取数据
            Object age = redisTemplate.boundValueOps("name").get();
            System.out.println("age ="+age);
        }
    
    }
  3. 编写配置文件

    #Redis 主机 ip
    spring.redis.host=1.117.144.59
    #Redis 主机端口
    spring.redis.port=6379
  4. 启动测试类

SpringBoot 整合 MyBatis

需要

应用 SpringBoot 整合 mybatis 框架,并实现 mybatis 数据库操作

思路

  1. 搭建 SpringBoot 工程(勾选SQL->MyBatis Framework+MySQL Driver
  2. 引入 mybatis 起步依赖,增加 mysql 驱动(主动曾经引入了)
  3. 编写 DataSource 和 MyBatis 相干配置
  4. 定义表和实体类
  5. 编写 dao 和 mapper 文件 / 纯注解开发
  6. 测试

实现 1 -mapper 文件开发

  1. 搭建 SpringBoot 工程(勾选SQL->MyBatis Framework+MySQL Driver
  2. 查看我的项目 pom 文件,发现多了上面两个依赖

            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>2.2.0</version>
            </dependency>
    
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <!--<scope>runtime</scope>-->
            </dependency>
  3. application.yaml 配置文件中编写 DataSource 和 MyBatis 相干配置

    #mysql datasource
    spring:
      datasource:
        url: jdbc:mysql:///Mybatis?serverTimezone=UTC
        username: root
        password: intmain()
        driver-class-name: com.mysql.cj.jdbc.Driver
    
    #mybatis
    mybatis:
      mapper-locations: classpath:xyz/rtx3090/springboot/mapper/UserMapper.xml
      type-aliases-package: xyz/rtx3090/sprigboot/model
  4. 创立实体类User

    public class User {
        private int id;
        private String name;
        private String pwd;
    
            //setter and getter
          //toString
    }
  5. 创立 UserMapper 接口

    @Mapper
    public interface UserMapper2 {public List<User> findAll();
    }
  6. 创立 UserMapper.xml 文件

    <?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="xyz.rtx3090.sprigboot.mapper.UserMapper2">
        <select id="findAll" resultType="user">
            select * from user;
        </select>
    </mapper>
  7. ApplicationTests 类中进行测试

    @SpringBootTest
    class ApplicationTests {
        @Resource
        private UserMapper2 userMapper2;
      
        @Test
        public void testFindAll2() {List<User> userList = userMapper2.findAll();
            System.out.println(userList);
        }
    }

实现 2 - 注解开发

  1. 搭建 SpringBoot 工程(勾选SQL->MyBatis Framework+MySQL Driver
  2. 查看我的项目 pom 文件,发现多了上面两个依赖

            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>2.2.0</version>
            </dependency>
    
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <!--<scope>runtime</scope>-->
            </dependency>
  3. application.yaml 配置文件中编写 DataSource 和 MyBatis 相干配置

    #mysql datasource
    spring:
      datasource:
        url: jdbc:mysql:///Mybatis?serverTimezone=UTC
        username: root
        password: intmain()
        driver-class-name: com.mysql.cj.jdbc.Driver
    
    #因为是注解开发,所以不须要配置 mybatis 相干内容
  4. 创立实体类User

    public class User {
        private int id;
        private String name;
        private String pwd;
    
            //setter and getter
          //toString
    }
  5. 创立 UserMapper 接口,采纳注解开发

    @Mapper
    public interface UserMapper {@Select("select * from user")
        public List<User> findAll();}
  6. ApplicationTests 类中进行测试

    @SpringBootTest
    class ApplicationTests {
    
        @Resource
        private UserMapper userMapper;
    
        @Test
        public void testFindAll() {List<User> userList = userMapper.findAll();
            System.out.println(userList);
        }
    }

SpringBoot 整合 Dubbo

需要

应用 SpringBoot 整合 Dubbo 分布式框架,并进行页面拜访

思路

创立三个工程项目,别离为:

  • 接口工程:寄存 bean 和业务接口
  • 服务提供者:业务接口的实现类,调用数据长久层
  • 服务消费者:解决浏览器客户端发送的申请,从注册核心调用服务提供者所提供的服务

实现

  1. 最终我的项目目录构造如图所示:

  2. 创立一般 Java Maven 工程08-springboot-dubbo-public-api-service

    1. 创立编写 service 接口StudentService

      package xyz.rtx3090.springboot.service;
      
      public interface StudentService {Integer queryAllStudentCount();
      }
  3. 创立 SpringBoot 工程 09-springboot-dubbo-provider(勾选Web->Spring Web 模版)

    1. 配置 pom 文件,引入所需依赖(留神批改原有的 springboot 框架 web 起步依赖)

              <!--springboot 框架 web 我的项目起步依赖 -->
              <dependency>
                  <groupId>org.springframework.boot</groupId>
                  <artifactId>spring-boot-starter-web</artifactId>
                  <exclusions>
                      <exclusion>
                          <groupId>org.slf4j</groupId>
                          <artifactId>slf4j-log4j12</artifactId>
                      </exclusion>
                  </exclusions>
              </dependency>
      
              <!--SpringBoot 框架起步测试依赖 -->
              <dependency>
                  <groupId>org.springframework.boot</groupId>
                  <artifactId>spring-boot-starter-test</artifactId>
                  <scope>test</scope>
              </dependency>
      
              <!--Dubbo 集成 SpringBoot 框架依赖 -->
              <dependency>
                  <groupId>com.alibaba.spring.boot</groupId>
                  <artifactId>dubbo-spring-boot-starter</artifactId>
                  <version>2.0.0</version>
              </dependency>
      
              <!-- 注册核心 -->
              <dependency>
                  <groupId>com.101tec</groupId>
                  <artifactId>zkclient</artifactId>
                  <version>0.10</version>
                  <exclusions>
                      <exclusion>
                          <groupId>org.slf4j</groupId>
                          <artifactId>slf4j-log4j12</artifactId>
                      </exclusion>
                  </exclusions>
              </dependency>
      
              <!-- 接口工程 -->
              <dependency>
                  <groupId>xyz.rtx3090.springboot</groupId>
                  <artifactId>08-springboot-dubbo-public-api-service</artifactId>
                  <version>1.0.0</version>
              </dependency>
    2. 实现上述的 service 接口StudentSerivceImpl

      package xyz.rtx3090.springboot.service.impl;
      
      import com.alibaba.dubbo.config.annotation.Service;
      import org.springframework.stereotype.Component;
      import xyz.rtx3090.springboot.service.StudentService;
      
      @Component
      // 裸露服务接口
      @Service(interfaceClass = StudentService.class, version = "1.0.0",timeout = 15000)
      public class StudentServiceImpl implements StudentService {
      
          // 这里须要注入 dao,咱们临时疏忽
      
          @Override
          public Integer queryAllStudentCount() {
              // 模仿 dao 操作,获取数据
              Integer count = 30;
      
              return count;
          }
      }
    3. 编写 springboot 配置文件application.properties

      # 设置内嵌 Tomcat 端口号
      server.port=8081
      #设置上下文根
      server.servlet.context-path=/provider
      
      #设置 dubbo 相干配置
      spring.application.name=09-springboot-dubbo-provider
      #申明以后工程是一个服务提供者
      spring.dubbo.server=true
      #设置注册核心
      spring.dubbo.registry=zookeeper://localhost:2181
  4. 创立 SpringBoot 工程 10-springboot-dubbo-consumer(勾选Web->Spring Web 模版)

    1. 配置 pom 文件,引入所需依赖(留神批改原有的 springboot 框架 web 起步依赖)

              <!--springboot 框架 web 我的项目起步依赖 -->
              <dependency>
                  <groupId>org.springframework.boot</groupId>
                  <artifactId>spring-boot-starter-web</artifactId>
                  <exclusions>
                      <exclusion>
                          <groupId>org.slf4j</groupId>
                          <artifactId>slf4j-log4j12</artifactId>
                      </exclusion>
                  </exclusions>
              </dependency>
      
              <!--springboot 我的项目起步测试依赖 -->
              <dependency>
                  <groupId>org.springframework.boot</groupId>
                  <artifactId>spring-boot-starter-test</artifactId>
                  <scope>test</scope>
              </dependency>
      
              <!--Dubbo 集成 SpringBoot 框架起步依赖 -->
              <dependency>
                  <groupId>com.alibaba.spring.boot</groupId>
                  <artifactId>dubbo-spring-boot-starter</artifactId>
                  <version>2.0.0</version>
              </dependency>
      
              <!-- 注册核心 -->
              <dependency>
                  <groupId>com.101tec</groupId>
                  <artifactId>zkclient</artifactId>
                  <version>0.10</version>
                  <exclusions>
                      <exclusion>
                          <groupId>org.slf4j</groupId>
                          <artifactId>slf4j-log4j12</artifactId>
                      </exclusion>
                  </exclusions>
              </dependency>
      
              <!-- 接口工程 -->
              <dependency>
                  <groupId>xyz.rtx3090.springboot</groupId>
                  <artifactId>08-springboot-dubbo-public-api-service</artifactId>
                  <version>1.0.0</version>
              </dependency>
    2. 编写 Controller 管制类StudentController

      package xyz.rtx3090.springboot.Controller;
      
      import com.alibaba.dubbo.config.annotation.Reference;
      import org.springframework.stereotype.Controller;
      import org.springframework.web.bind.annotation.RequestMapping;
      import org.springframework.web.bind.annotation.ResponseBody;
      import xyz.rtx3090.springboot.service.StudentService;
      
      @Controller
      @RequestMapping("/student")
      public class StudentController {@Reference(interfaceClass = StudentService.class,version = "1.0.0",check = false)
          private StudentService studentService;
      
          @RequestMapping("/count")
          @ResponseBody
          public String studentCount() {Integer count = studentService.queryAllStudentCount();
              return "学生总人数为:" + count;
          }
      }
    3. 编写 springboot 配置文件application.properties

      # 设置内嵌 Tomcat 端口号
      server.port=8080
      server.servlet.context-path=/consumer
      
      #设置 dubbo 配置
      spring.application.name=10-springboot-dubbo-consumer
      #指定注册核心
      spring.dubbo.registry=zookeeper://localhost:2181
  5. 顺次启动注册中 zookeeper、提供者工程09-springboot-dubbo-provider 和消费者工程10-springboot-dubbo-consumer,最初在浏览器输出http://localhost:8080/consumer/student/count,查看页面拜访后果:

SpringBoot 整合 SSM

需要

应用 SpringBoot 整合 SSM 框架,并进行页面拜访

思路

SpringBoot 自身曾经帮咱们整合并配置好 spring+springMVC 了,所以咱们只须要把更多的精力放到整合和配置 Mybatis 上就能够了

实现

  1. 筹备数据库

    CREATE DATABASE `springboot`;
    
    USE `springboot`;
    
    DROP TABLE IF EXISTS `t_user`;
    
    CREATE TABLE `t_user` (`id` int(11) NOT NULL AUTO_INCREMENT,
      `username` varchar(32) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
      `password` varchar(32) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
    
    insert  into `t_user`(`id`,`username`,`password`) values (1,'zhangsan','123'),(2,'lisi','234');
  2. 最终我的项目目录构造,如图所示:

  3. 创立 SpringBoot 我的项目,勾选 Web->Spring WebSQL->MyBatis Framework+MySQL Driver模版
  4. 编写配置 pom 文件,增加笼罩以下依赖

            <!--springboot 框架 web 我的项目起步依赖 -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
    
            <!--mybatis 集成 SpringBoot 框架依赖 -->
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>2.2.0</version>
            </dependency>
    
            <!--mysql 依赖 -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <scope>runtime</scope>
            </dependency>
    
            <!--springboot 框架起步测试依赖 -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
  5. model包下创立实体 JavaBen 类User

    package xyz.rtx3090.springboot.model;
    
    public class User {
        private int id;
        private String username;
        private String password;
            
          //setter and getter
          //toString
    }
  6. mapper包下创立 mapper 接口UserMapper

    package xyz.rtx3090.springboot.mapper;
    
    import org.apache.ibatis.annotations.Mapper;
    import xyz.rtx3090.springboot.model.User;
    
    @Mapper
    public interface UserMapper {
        // 依据 id 查问指定用户信息
        User queryUserById(int id);
    }
  7. resource目录下创立目录xyz/rtx3090/springboot/mapper,在其目录下创立 mapper 映射文件UserMapper.xml

    <?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="xyz.rtx3090.springboot.mapper.UserMapper">
        <!-- 依据 id 查问指定用户信息 -->
        <select id="queryUserById" resultType="user">
            select * from t_user where id = #{id};
        </select>
    </mapper>
  8. service目录下创立 service 类UserService

    package xyz.rtx3090.springboot.service;
    
    import xyz.rtx3090.springboot.model.User;
    
    public interface UserService {User queryUserById(int id);
    }
  9. service/impl目录下创立 service 实现类UserServiceImpl

    package xyz.rtx3090.springboot.service.impl;
    
    import org.springframework.stereotype.Service;
    import xyz.rtx3090.springboot.mapper.UserMapper;
    import xyz.rtx3090.springboot.model.User;
    import xyz.rtx3090.springboot.service.UserService;
    
    import javax.annotation.Resource;
    
    @Service
    public class UserServiceImpl implements UserService {
    
        @Resource
        private UserMapper userMapper;
    
        @Override
        public User queryUserById(int id) {User user = userMapper.queryUserById(id);
            return user;
        }
    }
  10. controller目录下创立 controller 管制类UserController

    package xyz.rtx3090.springboot.controller;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    import xyz.rtx3090.springboot.model.User;
    import xyz.rtx3090.springboot.service.UserService;
    
    import javax.annotation.Resource;
    
    /**
     * @author BernardoLi
     * @version 1.0.0
     * @ClassName UserController
     * @createTime 2021 年 09 月 12 日 03:29:00
     * @Description TODO
     */
    @Controller
    @RequestMapping("/user")
    public class UserController {
    
        @Resource
        private UserService userService;
    
        @RequestMapping("/queryUserById")
        @ResponseBody
        public String queryUserById(){
            // 模仿收到前端数据
            int id = 2;
            User user = userService.queryUserById(id);
            return user.toString();}
    }
  11. 批改 springboot 配置文件Application.properties

    #mysql datasource
    spring.datasource.url=jdbc:mysql:///springboot?serverTimezone=UTC
    spring.datasource.username=root
    spring.datasource.password=intmain()
    spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
    
    #mybatis
    #指定 mapper 文件门路
    mybatis.mapper-locations=classpath:xyz/rtx3090/springboot/mapper/UserMapper.xml
    #指定 resultType 类别名
    mybatis.type-aliases-package=xyz/rtx3090/springboot/model
  12. 进入 Application 类执行 main 办法,启动 springboot 我的项目,并在浏览器输出http://localhost:8080/user/queryUserById,查看页面后果

SpringBoot 集成 SSM+Redis+Dubbo+JSP

暂空

退出移动版