SpringBoot
SpringBoot概述
- Spring Boot是一个便捷搭建基于Spring工程的脚手架,主要的作用就是帮助开发人员快速的构建庞大的Spring项目,并且尽可能的减少一切xml配置,依赖管理
- 特点 :
- 创建独立的Spring应用,为所有Spring的开发者提供一个非常快速的广泛接受的入门体验
- 直接嵌入应用服务器,如tomcat,jetty,undertow等,不需要去部署war包
- 提供固定的启动器依赖去简化组件配置
- 自动配置Spring和其它有需要的第三方依赖
- 提供一些大型项目中常见的非功能性特性
- 绝对没有代码生成,也无需xml配置
SpringBoot快速入门
- 实现步骤
- 创建工程
- 添加依赖(启动器依赖,spring-boot-starter-web)
- 创建启动类
- 创建处理器Controller
- 测试
- Spring Boot 工程可以通过添加启动器依赖和创建启动引导类实现快速创建web工程
- spring-boot-starter-web默认的应用服务器端口是8080
pom.xml中的配置 :
<?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.5.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<artifactId>springbootdemo</artifactId>
<properties>
<java.version>13</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.5.0</version>
</plugin>
</plugins>
</build>
</project>
启动类 : SpringbootdemoApplication
package com.example.springbootdemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Spring Boot工程都有一个启动引导类 这是工程的入口类
* 并在引导类上添加@SpringBootApplication
*/
@SpringBootApplication
public class SpringbootdemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootdemoApplication.class, args);
}
}
Controller类 :
package com.example.springbootdemo.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@RequestMapping("hello")
public String hello(){
return "hello"+"world";
}
}
Java代码方式配置
- 目标 : 可以使用@Value获取配置文件配置项并结合@Bean注册组件到Spring
- java配置主要靠java类和一些注解,常用的注解是 :
- @Configration : 声明一个类作为配置类,代替xml文件
- @Bean : 声明在方法上,将方法的返回值加入Bean容器,代替 xml 中的 < bean > 标签
- @Value : 属性注入,声明在类成员数据变量上,可以把值直接注入到相应的数据变量中
- @PropertySource : 指定外部属性文件,从而可以使用文件中定义的数值,可以用来解耦合
- 步骤 :
- 添加依赖
- 创建数据库
- 创建数据库连接参数的配置文件jdbc.properties
- 创建配置类
- 改造处理器类注入数据源并使用
创建的配置类 : JdbcConfig
package com.example.springbootdemo.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import javax.sql.DataSource;
@Configuration
@PropertySource("classpath:jdbc.properties")
public class JdbcConfig {
@Value("${url}")
private String url;
@Value("${driver}")
private String driver;
@Value("${user}")
private String username;
@Value("${password}")
private String password;
@Bean
public DataSource getDataSource(){
DruidDataSource dataSource= new DruidDataSource();
dataSource.setUrl(""+url);
dataSource.setUsername(""+username);
dataSource.setDriverClassName(""+driver);
dataSource.setPassword(""+password);
return dataSource;
}
}
使用Controller的类来进行测试
package com.example.springbootdemo.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.sql.DataSource;
@RestController
public class HelloController {
@Autowired
private DataSource dataSource;
@RequestMapping("hello")
public String hello(){
System.out.println(dataSource);
return "hello"+"world";
}
}
SpringBoot属性注入方式
- 目标 ; 能够使用@ConfigurationProperties实现SpringBoot配置文件配置项读取和应用
- @ConfigurationProperties注解可以将SpringBoot的配置文件( 默认必须为 applocation.properties 或 application.yml )中的配置项读取到一个对象中
- 步骤:
- 将jdbc.properties 修改名称为application.properties
- 将@ConfigurationProperties(prefix=“a”)放在配置类中定义的获取方法上即可
- 测试
JdbcConfig类 : (只需要在配置文件中这样定义就好)
优雅永不过时
package com.example.springbootdemo.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
@Configuration
public class JdbcConfig {
@Bean
@ConfigurationProperties(prefix = "jdbc")
public DataSource getDataSource(){
return new DruidDataSource();
}
}
多个yml文件配置
- 目标 : 可以将多个yml文件在application.yml文件中配置激活
- yaml与properties配置文件除了展示形式不相同以外,其他功能和作用都是一样的,在项目中原来的读取方式不需要改变
- yml配置文件的特征
- 树状层级结构展示配置项
- 配置项之间如果有关系的话需要分行空两格
- 配置项如果有值的话,那么需要在 : 之后空一格再写配置项值
- 多个yml配置文件: 在SpringBoot中是被允许的,这些配置文件的名称必须为application-***.yml,并且配置文件必须要在application.yml配置文件中激活之后才可以使用
application.yml中的配置
jdbc:
url: jdbc:mysql://localhost:3306/spring_jdbc
user: root
password: root
driverClassName: com.mysql.cj.jdbc.Driver
#激活配置文件,需要指定其他的配置文件名称
spring:
profiles:
active: abc
自动配置原理
- 目标 : 了解Spring Boot项目的配置加载流程
- 在" META-INF\spring.factories 文件中定义了很多自动配置类,可以根据在pom.xml文件中添加的启动器依赖自动配置组件
- 通过如下流程可以去修改application配置文件,改变自动配置的组件默认参数
lombok应用
- 目标 : 使用lombok的注解实现pojo类的简化
- 使用Spring Boot整合SSM工程,需要使用到数据库数据
- 编写数据库表对应的实体类,一般情况下需要编写get/set/toString等这些方法会耗时并且会让实体类看起来比较臃肿,可以使用lombok插件对实体类进行简化
- lombok 是一个插件工具类包 : 提供一些注解@Data, @Getter等这些注解去简化实体类中的构造方法
- 在IDEA中安装lombok插件
- 添加lombok对应的依赖到项目pom.xml文件
- 改造实体类使用lombok注解
- 在Bean上使用:
- @Data : 自动提供getter和Setter,hashCode.equals.toString等方法
- @Getter : 自动提供getter方法
- @Setter : 自动提供setter方法
- @Slf4j : 自动在bean中提供log变量,其实用的是slf4j的日志功能
User类 :
package com.example.springbootdemo.pojo;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
//在编译阶段会根据注解自动生成对应的方法
@Data
@Slf4j
public class User {
private String name;
private int money;
}
SpringBoot整合SpringMVC端口和静态资源
- 目标 : 可以修改tomcat的端口和访问项目中的静态资源
- 修改tomcat端口 : 查询**Properties,设置配置项( 前缀+类变量名 ) 到application配置文件中
- 访问项目中的静态资源 :
- 静态资源放置的位置 :
- 放置静态资源并访问这些资源
application.yml中的配置 :
修改tomcat的端口 :
#tomcat端口修改
server:
port: 80
在SpringBoot项目中静态资源可以放置在如下目录 :
SpringBoot整合SpringMVC拦截器
- 目标 : 可以在SpringBoot项目中配置自定义SpringMVC拦截器
- 分析:
- 编写拦截器( 实现 Handlerinterceptor )
- 编写配置类实现 WebMvcConfigurer, 在该类中添加各种组件
- 测试
添加拦截器 :
package com.example.springbootdemo.config;
import com.example.springbootdemo.interceptor.Myintercepter;
import org.springframework.context.annotation.Bean;
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 MvcComfig implements WebMvcConfigurer {
//注册拦截器
@Bean
public Myintercepter myintercepter(){
return new Myintercepter();
}
//添加拦截器到SpringMvc的拦截器链
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(myintercepter()).addPathPatterns("/*");
}
}
application.yml 中的配置 :
#日志记录级别
logging:
level:
com: debug
org: info
SpringBoot整合事务和连接池
- 目标 : 配置SpringBoot自带默认的hikari数据库连接池和使用@Transactional注解进行事务配置
- 分析:
- 事务配置:
- 添加事务相关的启动器依赖,mysql相关依赖
- 编写业务类UserService使用事务注解@Transactional
- 数据库连接池hikari配置
- 只需要在application配置文件中指定数据库相关参数
- 事务配置:
application.yml 的配置:
#激活配置文件,需要指定其他的配置文件名称
spring:
profiles:
active: abc
datasource:
url: jdbc:mysql://localhost:3306/spring_jdbc?serverTimezone=GMT%2B8
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
SpringBoot整合Mybatis
- 目标 : 配置Mybatis在SpringBoot工程中的整合包,设置mybatis的实体类别名,输出执行sql语句配置项
- 分析:
- 添加启动器依赖 :
- 配置Mybatis : 实体类别名包,日志,映射文件等
- 配置MapperScan
pom.xml中添加的启动器依赖:
<!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
在Springboot的启动类添加mapper的扫描
package com.example.springbootdemo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Spring Boot工程都有一个启动引导类 这是工程的入口类
* 并在引导类上添加@SpringBootApplication
*/
@SpringBootApplication
//扫描mybatis所有的mapper
@MapperScan("com.example.springbootdemo.mapper")
public class SpringbootdemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootdemoApplication.class, args);
}
}
application.yml中的配置:
mybatis:
#配置实体类别名包路径
type-aliases-package: com.example.pojo
#映射文件路径
# mapper-locations: classpath:mapper/*.xml
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
Springboot整合通用Mapper
- 目标 : 配置通用的Mapper组件到SpringBoot项目中并使用Mapper< I >接口
- 分析:
- 通用Mapper : 可以实现自动拼接sql语句, 所有的Mapper都不需要编写任何方法也就是不要编写sql语句,可以提高开发效率
- 添加启动器依赖
- 改造UserMapper继承Mapper< User >
- 修改启动引导类Application中的Mapper扫描注解
- 修改User实体类添加 jpa 注解
- 改造UserService实现业务功能
pom.xml中添加的依赖:
<!-- https://mvnrepository.com/artifact/tk.mybatis/mapper-spring-boot-starter -->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>2.1.5</version>
</dependency>
UserMapper 的接口类中继承Mapper类
package com.example.springbootdemo.mapper;
import com.example.springbootdemo.pojo.User;
import tk.mybatis.mapper.common.Mapper;
public interface UserMapper extends Mapper<User> {
}
启动类中的@MapperScan注解需要进行替换
package com.example.springbootdemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import tk.mybatis.spring.annotation.MapperScan;
@MapperScan("com.example.springbootdemo.mapper")
public class SpringbootdemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootdemoApplication.class, args);
}
}
Spring Boot 整合Junit
- 目标 : 在SpringBoot项目中使用Junit进行单元测试UserService方法
- 分析
- 添加启动器依赖 spring-boot-starter-test
- 编写测试类
测试类的代码:
package com.example.springbootdemo.service;
import com.example.springbootdemo.pojo.User;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.jupiter.api.Assertions.*;
@RunWith(SpringRunner.class)
@SpringBootTest
class UserServiceTest {
@Autowired
private UserService userService;
@Test
void findById() {
User byId = userService.findById(2);
System.out.println(byId);
}
@Test
void saveUser() {
User user = new User();
user.setName("th");
user.setMoney(200);
userService.saveUser(user);
}
}
SpringBoot整合redis
- 目标 : 在SpringBoot中使用Junit测试RedisTemplate的使用
- 分析 :
- 添加启动器依赖 : spring-boot-data-redis
- 配置application.yml中修改redis的连续参数 : (redis需要启动)
- 编写测试类应用RedisTemplate操作redis中的5种数据类型
pom.xml中添加依赖:
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.4.5</version>
</dependency>
编写的测试类:
package com.example.springbootdemo.redis;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
import java.util.Set;
@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisTest {
@Autowired
private RedisTemplate redisTemplate;
@Test
public void test(){
//String
// redisTemplate.opsForValue().set("str","heima");
redisTemplate.boundValueOps("str").set("he");
System.out.println("aaa");
System.out.println(redisTemplate.opsForValue().get("str"));
//hash 散列表
redisTemplate.boundHashOps("h_key").put("name","zhangsan");
redisTemplate.boundHashOps("h_key").put("money","2000");
//获取所有域
Set h_key = redisTemplate.boundHashOps("h_key").keys();
System.out.println("散列的所有域" + h_key);
//获取所有值
List h_key1 = redisTemplate.boundHashOps("h_key").values();
System.out.println("散列的所有域的值" + h_key1);
//list 列表
redisTemplate.boundListOps("key1").leftPush("s");
redisTemplate.boundListOps("key1").leftPush("b");
redisTemplate.boundListOps("key1").leftPush("c");
List key1 = redisTemplate.boundListOps("key1").range(0, -1);
System.out.println("list列表中的所有元素" + key1);
//set 集合
redisTemplate.boundSetOps("s_key").add("a","b","c");
Set s_key = redisTemplate.boundSetOps("s_key").members();
System.out.println("集合中的元素有" + s_key);
//sorted_set 有序集合
redisTemplate.boundZSetOps("s_key1").add("a",10);
redisTemplate.boundZSetOps("s_key1").add("b",20);
redisTemplate.boundZSetOps("s_key1").add("c",30);
Set s_key1 = redisTemplate.boundZSetOps("s_key1").range(0, -1);
System.out.println("有序集合中的所有元素" + s_key1);
}
}
SpringBoot项目部署
- 目标 : 将SpringBoot的项目使用maven指令打成jar包并运行测试
- 分析:
- 需要添加打包组件将项目中的资源,配置,依赖包打包到一个jar包中,可以使用maven的package
- 部署 : java-jar 包名