6.SSM-SpringBoot

1.SpringBoot简介

1.1 入门案例

1.新建SpringBoot项目
若是start.spring.io连接超时可采用https://start.aliyun.com/代替
请添加图片描述

请添加图片描述

2.编写BookController

package com.example.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 springboot";
    }
}

3.启动springboot
运行Springboot01Application.java

遇到问题:ERROR 5328 — [ main] o.a.catalina.core.AprLifecycleListener
原因是C:\Windows\System32下缺少的tcnative-1.ddl
去http://archive.apache.org/dist/tomcat/tomcat-connectors/native/1.2.14/binaries/下载插件: tomcat-native-1.2.14-win32-bin.zip
解压后将tcnative-1.ddl拷贝到C:\Windows\System32目录下重启项目即可

最简单SpringBoot程序所包含的基础文件
pom.xml
Application类

Spring程序与SpringBoot程序对比

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

也可以直接在Sping官网创建项目
https://start.spring.io/
下载并导入idea

1.2 SpringBoot项目快速启动

① 对SpringBoot项目打包(执行Maven构建指令package)
maven ==> package打包成jar包
打好的jar包在target目录下

② 执行启动指令:
java -jar .\springboot_01-0.0.1-SNAPSHOT.jar

注意事项:jar支持命令行执行需要maven插件支持,请确认打包时是否具有SpringBoot对应的maven插件

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <version>2.3.7.RELEASE</version>
    <configuration>
        <mainClass>com.example.Springboot01Application</mainClass>
    </configuration>
    <executions>
        <execution>
            <id>repackage</id>
            <goals>
                <goal>repackage</goal>
            </goals>
        </execution>
    </executions>
</plugin>

1.3 SpringBoot概述

SpringBoot是由Pivotal团队提供的全新框架,其设计目的是用来简化Spring应用的初始搭建以及开发过程

  • Spring程序缺点
    • 配置繁琐
    • 依赖设置繁琐
  • SpringBoot程序有点
    • 自动配置‘
    • 起步依赖(简化依赖配置)
    • 辅助功能(内置服务器,…)

SpringBoot起步依赖

  • starter

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

    • 所有 SpringBoot 项目要继承的项目,定义了若干个坐标版本号(依赖管理,而非依赖),以达到减少依赖冲突的目的
    • spring-boot-starter-parent (2.5.0)与 spring-boot-starter-parent (2.4.6)共计57处坐标版本不同
  • 实际开发

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

1.4 SpringBoot启动程序

启动方式

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Springboot01Application {

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

}

SpringBoot在创建项目时,采用jar的打包方式
SpringBoot的引导类是项目的入口,运行main方法就可以启动项目

使用Jetty代替Tomcat
使用maven依赖管理变更起步依赖项

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jetty</artifactId>
</dependency>

Jetty比Tomcat更轻量级,可扩展性更强(相当于Tomcat),谷歌应用引擎(GAE)已经全面借还为Jetty

2. 基础配置

修改服务器端口
SpringBoot提供了多种属性配置方式
① application.properties
server.port=80

② application.yml (主要使用方式)
server:
 port: 81

③ application.yaml
server:
 port: 82

SpringBoot配置文件加载顺序
application.properties > application.yml > application.yaml

2.1 yaml

YAML 一种数据序列化格式

  • 优点:

    • 容易阅读
    • 容易与脚本语言互动
    • 以数据为核心,重数据轻格式
  • YAML文件扩展名

    • .yml(主流)
    • .yaml

yaml语法规则
1.大小写敏感
2.属性层级关系使用多行描述,每行结尾使用冒号结束
3.使用缩进表示层级关系,同层级左侧对齐,只允许使用空格(不允许使用Tab键)
4.空格的个数并不重要,只要保证同层级的左侧对齐即可。
5.属性值前面添加空格(属性名与属性值之间使用冒号+空格作为分隔)
6.#表示注释
核心规则:数据前面要加空格与冒号隔开
7.数组数据在数据书写位置的下方使用减号作为数据开始符号,每行书写一个数据,减号与数据间空格分隔,例如

enterprise:
  name: example
  age: 16
  tel: 123456789
  subject:
    - Java
    - 前端
    - 大数据

YAML数据读取方式(3种)
1.使用@Value读取单个数据,属性名引用方式:${一级属性名.二级属性名…}
2.封装全部数据到Environment对象
3.自定义对象封装指定数据

实验
需要读取的配置文件数据

server:
  port: 80

lesson: SpringBoot

enterprise:
  name: example
  age: 16
  tel: 123456789
  subject:
    - Java
    - 前端
    - 大数据

① Enterprise对象用于加载enterprise数据

package com.example.domain;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@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=" + Arrays.toString(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;
    }
}

② Controller类

package com.example.controller;

import com.example.Springboot01Application;
import com.example.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;

//    方式二
    @Autowired
    private Environment environment;

//    方式三
    @Autowired
    private Enterprise enterprise;

    @GetMapping("{id}")
    public String getById(@PathVariable Integer id){
        System.out.println("id ==> " + id);
        System.out.println(lesson);
        System.out.println(port);
        System.out.println(subject_00);
        System.out.println("-------------------");
        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]"));
        System.out.println("------------------");
        System.out.println(enterprise.toString());
        return "hello springboot";
    }
}

③ 测试:发送get请求:http://localhost/books/2

自定义对象封装数据警告解决方案

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

2.2 多环境开发

多环境开发配置

#设置启用的环境
spring:
  profiles:
    active: pro

---
#开发
spring:
  profiles: dev
server:
  port: 80
---
#生产
spring:
  profiles: pro
server:
  port: 81


---
#测试
spring:
  profiles: test
server:
  port: 82

多环境命令行启动参数设置
打包之前先把idea编码设置为utf-8
maven ==> clean 清除记录
maven ==> package 打包

带参数启动SpringBoot

java -jar .\springboot_01-0.0.1-SNAPSHOT.jar --spring.profiles.active=dev

java -jar .\springboot_01-0.0.1-SNAPSHOT.jar --server.port=88

java -jar .\springboot_01-0.0.1-SNAPSHOT.jar --server.port=88 --spring.profiles.active=dev

参数加载优先级:
https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.external-config

2.3 Maven与SpringBoot多环境兼容

① Maven中设置多环境属性

<profiles>
    <!--开发环境-->
    <profile>
        <id>dev</id>
        <properties>
            <profile.active>dev</profile.active>
        </properties>
    </profile>
    <!--生产环境-->
    <profile>
        <id>pro</id>
        <properties>
            <profile.active>pro</profile.active>
        </properties>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
    </profile>
    <!--测试环境-->
    <profile>
        <id>test</id>
        <properties>
            <profile.active>test</profile.active>
        </properties>
    </profile>
</profiles>

② SpringBoot中引用Maven属性

#设置启用的环境
spring:
  profiles:
    active: ${profile.active}

---
#开发
spring:
  profiles: dev
server:
  port: 80
---
#生产
spring:
  profiles: pro
server:
  port: 81


---
#测试
spring:
  profiles: test
server:
  port: 82

③ 对资源文件开启默认占位符的解析

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-resources-plugin</artifactId>
    <version>3.2.0</version>
    <configuration>
        <encoding>UTF-8</encoding>
        <useDefaultDelimiters>true</useDefaultDelimiters>
    </configuration>
</plugin>

④ 打包

2.4 配置文件分类

  • SpringBoot中4级配置文件

    • 1级:classpath:application.yml
    • 2级:classpath:config/application.yml
    • 3级:file :application.yml
    • 4级:file :config/application.yml
      说明:级别越高优先级越高
  • 作用

    • 3级与4级留作系统打包后设置通用属性
    • 1级与2级用于系统开发阶段设置通用属性

3.整合第三方技术

3.1 整合JUnit

BookService

package com.example.service;

public interface BookService {
    public void save();
}

BookServiceImpl

package com.example.service.impl;

import com.example.service.BookService;
import org.springframework.stereotype.Service;

@Service
public class BookServiceImpl implements BookService {
    @Override
    public void save() {
        System.out.println("book save ...");
    }
}

SpringBott整合JUnit(test包下自动生成的测试类)

package com.example;

import com.example.service.BookService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class Springboot01ApplicationTests {

    @Autowired
    private BookService bookService;
    
    @Test
    public void testSave(){
        bookService.save();
    }

}

测试类注解
@SpringBootTest
设置JUnit加载的SpringBoot启动类

3.2 整合Mybatis

① 新建工程
勾选Mybatis Framework 和 MySQL Driver
请添加图片描述

② 环境准备
Book类

package com.example.domain;

public class Book {
    private Integer id;
    private String name;
    private String type;
    private String description;

    @Override
    public String toString() {
        return "Book{" +
                "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;
    }
}

BookDao接口(需要加@Mapper注解)

package com.example.dao;

import com.example.domain.Book;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

@Mapper
public interface BookDao {
    @Select("select * from tbl_book where id = #{id}")
    public Book getById(Integer id);
}

② 配置文件(application.yml)根据自己的数据库设置参数

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://192.168.1.224:3306/ssm_db?characterEncoding=utf8
    username: root
    password: 123456

③ 测试

package com.example;

import com.example.dao.BookDao;
import com.example.domain.Book;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class Springboot02ApplicationTests {

    @Autowired
    private BookDao bookDao;

    @Test
    void testGetById() {
        Book book = bookDao.getById(1);
        System.out.println(book);
    }

}

如果出现空指针异常,则SpringBoot改为2.5.0版本
springboot2.4.3以前的版本url需要加时区
如:url: jdbc:mysql://192.168.1.224:3306/ssm_db?serverTimezone=UTC

3.2.1 使用druid数据源

① 添加坐标

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.16</version>
</dependency>

② 修改配置

spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://192.168.1.224:3306/ssm_db?characterEncoding=utf8
    username: root
    password: 123456

③ 运行测试类

3.3 基于SpringBoot的SSM整合案例

1.pom.xml
配置起步依赖,必要的资源坐标(druid)

2.application.yml
设置数据源、端口等

3.配置类
全部删除

4.dao
设置@Mapper

5.测试类

6.页面
放在resources目录下的static目录中

实验
① 创建项目,勾选Spring Web,Mybatis Framework 和 MySQL Driver

② 把springmvc做的项目中dao,domain,exception,controller,service拷贝到com.example包下

③ 添加依赖

<!--TODO 添加必要的依赖坐标-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.16</version>
</dependency>

③ 配置类(application.yml)

# DOTO 配置数据源相关信息
server:
  port: 80
spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://192.168.1.224:3306/ssm_db
    username: root
    password: 123456

④ BookDao设置@Mapper

//TODO 添加@Mapper
@Mapper
public interface BookDao 

⑤ 测试类测试功能

package com.example.service;



import com.example.domain.Book;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;

@SpringBootTest
public class BookServiceTest {
    @Autowired
    private BookService bookService;

    @Test
    public void testGetById(){
        Book book = bookService.getById(1);
        System.out.println(book);
    }

    @Test
    public void testGetAll(){
        List<Book> list = bookService.getAll();
        System.out.println(list);
    }
}

⑥ 将springMVC的项目中的页面拷贝到resources.static包下

⑦ 访问:http://localhost/pages/books.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值