SpringBoot快速入门

1、SpringBoot简介

SpringBoot概述

  • SpringBoot是由Pivotal团队提供的全新框架,其设计目的是用来简化Spring应用的初始搭建以及开发过程
  • Spring程序缺点
    1. 配置繁琐
    2. 依赖设置繁琐
  • SpringBoot程序优点
    1. 自动配置
    2. 起步依赖(简化依赖配置
      <?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>
          <parent>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-starter-parent</artifactId>
              <version>2.7.12</version>
              <relativePath/> <!-- lookup parent from repository -->
          </parent>
          <dependencies>
              <dependency>
                  <groupId>org.springframework.boot</groupId>
                  <artifactId>spring-boot-starter-test</artifactId>
                  <scope>test</scope>
              </dependency>
          </dependencies>
      </project>
      
    3. 辅助功能(内置服务器,……

SpringBoot起步依赖

  • starter

    • SpringBoot中常见项目名称,定义了当前项目使用的所有项目坐标,已达到 减少依赖配置 的目的
  • parent

    • 所有SpringBoot项目要继承的项目,定义了若干个坐标版本号(依赖管理,并非依赖),已达到减少依赖冲突的目的
  • 实际开发

    • 使用任意坐标时,仅数协GAV中的G和A,V由SpringBoot提供
    • 如发生坐标错误,再指定version(要小心版本冲突)

SpringBoot程序启动

  • 启动方式

    package com.springboot_01_quickstart;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class Springboot01QuickstartApplication {
    
        public static void main( String[] args ) {
            SpringApplication.run(Springboot01QuickstartApplication.class, args);
        }
    
    }
    
  • SpringBoot在创建项目时,采用jar的打包方式

  • SpringBoot的引导类是项目的入口,运行main方法就可以启动项目

入门案例

基于idea开发SpringBoot程序需要确保联网且能够加载到程序框架结构

  • 新建一个SpringBoot程序
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述

  • 创建第一个SpringBoot程序(controller.BookController)

    package com.springboot_01_quickstart.controller;
    
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    @RequestMapping("/books")
    public class BookController {
        @GetMapping("/{id}")
        public String getById( @PathVariable Integer id ){
            System.out.println("id==》"+id);
            return "hello,spring boot!";
        }
    }
    
  • 运行程序
    在这里插入图片描述
    在这里插入图片描述

  • 测试(http://localhost:8080/books/1
    在这里插入图片描述

  • 最简SpringBoot程序包含的基础文件

    1. pom.xml文件
    2. Application类
  • Spring程序与SpringBoot程序对比

    类/配置文件SpringSpringBoot
    pom文件中的坐标手工添加勾选添加
    web3.0配置类手工制作
    Spring/SpringMVC配置类手工制作
    控制器手工制作手工制作

SpringBoot项目快速启动

运行电脑需要有jdk环境

  • 打包SpringBoot项目
    在这里插入图片描述
  • 找到项目目录(输入cmd
    在这里插入图片描述
  • 启动SpringBoot项目(java -jar 项目名称.jar
    在这里插入图片描述
  • 测试(http://localhost:8080/books/12
    在这里插入图片描述

2、基础配置

  • SpringBoot提供了多种属性配置方式
    • application.properties

      server.port=80
      

      在这里插入图片描述
      在这里插入图片描述

    • application.yml

      server:
      	port: 81
      

      在这里插入图片描述

    • application.yaml

      server:
      	port: 82
      

      在这里插入图片描述

  • 配置文件加载顺序
    1. application.properties
    2. application.yml
    3. application.yaml

自动提示功能消失解决方案

  1. File————Project Structure
    在这里插入图片描述

  2. Facets——选择项目
    在这里插入图片描述

  3. 点击+————选择要添加的文件类型
    在这里插入图片描述

yaml语法

  • YAML:一种数据序列化格式
  • 优点:
    • 容易阅读
    • 容易与脚本语言交互
    • 以数据为核心,重数据轻格式
  • YAML文件扩展名
    • .yml(主流)
    • .yaml
  • yaml语法规则:
    1. 大小写敏感
    2. 属性层级关系使用多行描述,每行结尾使用冒号结束
    3. 使用缩进表示层级关系,同层级左侧对齐,只允许使用空格(不允许使用Tab键)
    4. 属性值前面添加空格(属性名与属性值之间使用冒号+空格作为分隔)
    5. # 表示注释
    6. 核心规则:数据前面要加空格与冒号隔开
  • yaml数组数据: 数组数据在数据书写位置的下方使用减号作为数据开始符号,每行书写一个数据,减号与数据间空格分隔
    study:
      - java
      - 前端
      - 运维
    

yaml数据读取方式

建立一个application.yaml文件内容如下
在这里插入图片描述

  • 使用@Value读取单个数据,属性名引用方式:${一级属性名.二级属性名……}

    package com.springboot_03_read_data.controller;
    
    import com.springboot_03_read_data.domain.Enterprise;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.core.env.Environment;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    @RequestMapping("/books")
    public class BookController {
    
        @Value("${lesson}")
        private String lesson;
        @Value("${server.port}")
        private Integer port;
        @Value("${enterprise.subject[0]}")
        private String subject_00;
    
        @GetMapping("/{id}")
        public String getById( @PathVariable Integer id ){
            System.out.println(lesson);
            System.out.println(port);
            System.out.println(subject_00);
            return "hello,spring boot!";
        }
    }
    
  • 封装全部数据到Environment对象(@Autowired自动装配

    package com.springboot_03_read_data.controller;
    
    import com.springboot_03_read_data.domain.Enterprise;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.core.env.Environment;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    @RequestMapping("/books")
    public class BookController {
        @Autowired
        private Environment environment;
    
        @GetMapping("/{id}")
        public String getById( @PathVariable Integer id ){
            System.out.println(environment.getProperty("lesson"));
            System.out.println(environment.getProperty("server.port"));
            System.out.println(environment.getProperty("enterprise.age"));
            System.out.println(environment.getProperty("enterprise.subject[1]"));
            return "hello,spring boot!";
        }
    }
    
  • 自定义对象封装指定数据

    • 自定义对象封装数据警告解决方案 添加依赖
      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-configuration-processor</artifactId>
      </dependency>
      
    1. 创建一个实体类
      • @ConfigurationProperties(prefix = “加载的对象名”)
      package com.springboot_03_read_data.domain;
      
      import org.springframework.boot.context.properties.ConfigurationProperties;
      import org.springframework.stereotype.Component;
      
      @Component
      @ConfigurationProperties(prefix = "enterprise")
      public class Enterprise {
          private String name;
          private Integer age;
          private String tel;
          private String[] subject;
      
          @Override
          public String toString( ) {
              return "Enterprise{" +
                      "name='" + name + '\'' +
                      ", age=" + age +
                      ", tel='" + tel + '\'' +
                      ", subject='" + subject + '\'' +
                      '}';
          }
      
          public String getName( ) {
              return name;
          }
      
          public void setName( String name ) {
              this.name = name;
          }
      
          public Integer getAge( ) {
              return age;
          }
      
          public void setAge( Integer age ) {
              this.age = age;
          }
      
          public String getTel( ) {
              return tel;
          }
      
          public void setTel( String tel ) {
              this.tel = tel;
          }
      
          public String[] getSubject( ) {
              return subject;
          }
      
          public void setSubject( String[] subject ) {
              this.subject = subject;
          }
      }
      
    2. 使用配置
      package com.springboot_03_read_data.controller;
      
      import com.springboot_03_read_data.domain.Enterprise;
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.beans.factory.annotation.Value;
      import org.springframework.core.env.Environment;
      import org.springframework.web.bind.annotation.GetMapping;
      import org.springframework.web.bind.annotation.PathVariable;
      import org.springframework.web.bind.annotation.RequestMapping;
      import org.springframework.web.bind.annotation.RestController;
      
      @RestController
      @RequestMapping("/books")
      public class BookController {
          @Autowired
          private Enterprise enterprise;
      
          @GetMapping("/{id}")
          public String getById( @PathVariable Integer id ){
      
              System.out.println(enterprise);
              return "hello,spring boot!";
          }
      }
      

多环境启动

  • yaml多环境启动(三个-表示不同模块)

    #设置启用的环境
    spring:
      profiles:
        active: test			//启动的环境名称
    
    
    ---
    #开发
    server:
      port: 80
    
    spring:
      config:
        activate:
          on-profile: dev		//环境名称
    ---
    #生产
    server:
      port: 81
    
    spring:
      config:
        activate:
          on-profile: pro		//环境名称
    
    ---
    #测试
    server:
      port: 82
    
    
    spring:
      config:
        activate:
          on-profile: test		//环境名称
    
  • properties文件多环境启动

    • 主启动配置文件application.properties
      #设置启用饿环境
      spring.profiles.active=pro
      
    • 环境分类配置文件application-pro.properties
      server.port=8080
      
    • 环境分类配置文件application-dev.properties
      server.port=8081
      
    • 环境分类配置文件application-test.properties
      server.port=8082
      

多环境启动命令格式

  • 将上一个demo中的properties文件放在bak文件夹下(这里是yaml切换方法
    在这里插入图片描述
  • 打包在这里插入图片描述
  • 打开文件目录执行cmd
    在这里插入图片描述
  • 启动项目:java -jar springboot_04_profile-0.0.1-SNAPSHOT.jar --spring.profiles.active=test
    • –后面对应我们的配置多级用 . 隔开最后用 = 赋值
      在这里插入图片描述
  • 设置端口参数(--server.port=88
    在这里插入图片描述

配置文件分类

  • SpringBoot中4级配置文件
    1. file: config/application.ymal(最高
    2. file: application.yml
    3. classpath: config/application.yml
    4. classpath:application.yml (最低
  • 作用
    • 1级与2级留做系统打包后设置通用属性
      在这里插入图片描述

    • 3级4级用于系统开发阶段设置通用属性
      在这里插入图片描述

3、整合第三方技术

整合Junit

如果测试类在SpringBoot启动类的包或子包中,可以省略启动类配置,也就是省略classes的设定

  • 添加一个全新的模块(直接完成)
    在这里插入图片描述

  • 创建BookService

    package com.springboot_06_test;
    
    import com.springboot_06_test.service.BookService;
    import org.junit.jupiter.api.Test;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    
    @SpringBootTest
    class Springboot06TestApplicationTests {
    
        @Autowired
        private BookService bookService;
    
        @Test
        void contextLoads( ) {
            bookService.save();
        }
    
    }
    
    
  • 创建BookServiceImpl

    package com.springboot_06_test.service.impl;
    
    import com.springboot_06_test.service.BookService;
    import org.springframework.stereotype.Service;
    
    @Service
    public class BookServiceImpl implements BookService {
        @Override
        public void save( ) {
            System.out.println("book service is running ···");
        }
    }
    
  • SpringBoot整合Junit

    package com.springboot_06_test;
    
    import com.springboot_06_test.service.BookService;
    import org.junit.jupiter.api.Test;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    
    @SpringBootTest
    class Springboot06TestApplicationTests {
    
        @Autowired
        private BookService bookService;		//把要测试的资源注入进去
    
        @Test
        public void testSave( ) {
            bookService.save();
        }
    
    }
    
  • 名称:@SpringBootTest

  • 类型:测试类注解

  • 位置:测试类上方

  • 作用:设置Junit加载的SpringBoot启动类

  • 范例:

    @SpringBootTest(classes = Springboot06TestApplication.class)
    class Springboot06TestApplicationTests {}
    
  • 相关属性:classes:设置SpringBoot启动类

基于SpringBoot实现SSM整合

  • SpringBoot整合Spring (不存在)
  • SpringBoot整合SpringMVC (不存在)
  • SpringBoot整合MyBatis 主要
  • Spring整合MyBatis(复习)
    • SpringConfig
      • 导入JdbcConfig
      • 导入MyBatisConfig
    • JDBCConfig
      • 定义数据源
    • MyBatisConfig
      • 定义SqlSessionFactoryBean
      • 定义映射配置

整合MyBatis

  1. 搭建数据库

    CREATE DATABASE `ssm_db`;
    
    USER `ssm_db`;
    
    CREATE TABLE `tbl_user`(
    	`id` INT(20) NOT NULL PRIMARY KEY,
    	`name` VARCHAR(30) DEFAULT NULL,
    	`type` VARCHAR(30) DEFAULT NULL,
    	`description` VARCHAR(30) DEFAULT NULL
    )ENGINE=INNODB DEFAULT CHARSET=utf8;
    
    
    INSERT INTO `tbl_user` (`id`,`name`,`type`,`description`) VALUES
    (1,'Java学不会','1','123456'),
    (2,'张三','2','123456'),
    (3,'李四','1','123456')
    
  2. 创建一个全新的模块
    在这里插入图片描述

  3. 设置数据源参数(application.yml)

    spring:
      datasource:
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://localhost:3306/ssm_db
        username: root
        password: 123456
        type: com.alibaba.druid.pool.DruidDataSource
    
  4. 编写实体类

    package com.springboot_07_mybatis.domain;
    
    public class User {
        private Integer id;
        private String name;
        private String type;
        private String description;
    
        @Override
        public String toString( ) {
            return "User{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", type='" + type + '\'' +
                    ", description='" + description + '\'' +
                    '}';
        }
    
        public Integer getId( ) {
            return id;
        }
    
        public void setId( Integer id ) {
            this.id = id;
        }
    
        public String getName( ) {
            return name;
        }
    
        public void setName( String name ) {
            this.name = name;
        }
    
        public String getType( ) {
            return type;
        }
    
        public void setType( String type ) {
            this.type = type;
        }
    
        public String getDescription( ) {
            return description;
        }
    
        public void setDescription( String description ) {
            this.description = description;
        }
    }
    
    
  5. 编写dao层

    package com.springboot_07_mybatis.dao;
    
    import com.springboot_07_mybatis.domain.User;
    import org.apache.ibatis.annotations.Mapper;
    import org.apache.ibatis.annotations.Select;
    
    @Mapper
    public interface UserDao {
        @Select("select * from tbl_user where id = #{id}")
        public User getById( Integer id);
    }
    
  6. 测试类

    package com.springboot_07_mybatis;
    
    import com.springboot_07_mybatis.dao.UserDao;
    import com.springboot_07_mybatis.domain.User;
    import org.junit.jupiter.api.Test;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    
    @SpringBootTest
    class Springboot07MybatisApplicationTests {
    
        @Autowired
        private UserDao bookDao;
    
        @Test
        void testGetById( ) {
            User book = bookDao.getById(1);
            System.out.println(book);
        }
    
    }
    
  7. 运行结果
    在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小吴在敲Bug

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值