SpringBoot整合实战
一、SpringBoot整合Redis
1、在pom.xml中导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.3.7.RELEASE</version>
</dependency>
2、在application.properties中编写相关配置
spring.redis.host=127.0.0.1
spring.redis.port=6379
3、在测试类中进行测试
package com.kuang;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.kuang.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
@SpringBootTest
class Springboot09RedisApplicationTests {
@Autowired
@Qualifier("redisTemplates")
private RedisTemplate redisTemplate;
@Test
void contextLoads() {
/*//获取redis的连接对象
RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
connection.flushDb();
connection.flushAll();*/
redisTemplate.opsForValue().set("mykey","kuangshen");
System.out.println(redisTemplate.opsForValue().get("mykey"));
}
@Test
public void test() throws JsonProcessingException {
//真实的开发一般都使用json来传递对象
User user = new User("狂神说", 3);
String jsonUser = new ObjectMapper().writeValueAsString(user);
redisTemplate.opsForValue().set("user",jsonUser);
System.out.println(redisTemplate.opsForValue().get("user"));
}
}
二、SpringBoot整合Swagger2
前后端分离开发,后端需要编写接口说明文档,会耗时比较多的时间。
swagger是一个用于生成服务器接口的规范性文档、并且能够对接口进行测试的工具。
1、作用
- 生成接口文档
- 可以对接口进行测试
2、整合
SpringBoot 2.3.7.RELEASE
2.1、在pom.xml中添加依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>1.9.6</version>
</dependency>
2.2、创建Swagger的配置(Java配置方式)
package com.zyb.xmmall.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
@Configuration
public class Swagger2Config {
/*封装接口文档信息*/
@Bean
public Docket getDocket(){
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select()
.apis(RequestHandlerSelectors.basePackage("com.zyb.xmmall.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo(){
return new ApiInfoBuilder().title("《小米商城后端接口说明》")
.description("详细描述了后端提供给前端的接口的说明")
.contact(new Contact("管理员","",""))
.version("v 1.0.0")
.build();
}
}
2.3、编写测试的Controller类
@Api(tags="测试接口模板")
@Controller
@RequestMapping("api/v1")
public class TestController {
@ApiOperation("test测试")
@RequestMapping(value="/ha",method=RequestMethod.GET)
@ResponseBody
public String test(){
return "test测试成功";
}
@ApiOperation("Area删除")
@RequestMapping(value="/a",method=RequestMethod.POST)
@ResponseBody
public String ha(){
return "Area删除成功";
}
}
2.4、SpringBoot启动类
package com.zyb.xmmall;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@SpringBootApplication
@EnableSwagger2
public class XmmallApplication {
public static void main(String[] args) {
SpringApplication.run(XmmallApplication.class, args);
}
}
2.5、项目运行截图
http://localhost:8080/swagger-ui.html
http://localhost:8080/doc.html
三、SpringBoot整合EasyExcel
1、在pom.xml中导入依赖
<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>2.2.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.0.5</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
</dependencies>
2、在application.properties中编写相关配置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/testexcel?characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=123456
mybatis.type-aliases-package=com.example.pojo
mybatis.mapper-locations=classpath:mapper/*.xml
logging.level.com.example.dao=debug
3、编写实体类
package com.example.pojo;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;
@Data
public class Student {
@ExcelProperty(value = "编号",index = 0)
private Integer id;
@ExcelProperty(value = "姓名",index = 1)
private String name;
@ExcelProperty(value = "性别",index = 2)
private String sex;
@ExcelProperty(value = "年龄",index = 3)
private Integer age;
}
4、编写dao层
package com.example.dao;
import com.example.pojo.Student;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface StudentDao {
//查询全部学生信息
List<Student> selectAll();
//批量插入学生数据
int saveStudent(List<Student> studentList);
}
5、在resources下mapper文件中编写StudentMapper.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="com.example.dao.StudentDao">
<resultMap id="stuMap" type="com.example.pojo.Student">
<id column="id" property="id"/>
<result column="name" property="name"/>
<result column="sex" property="sex"/>
<result column="age" property="age"/>
</resultMap>
<select id="selectAll" resultMap="stuMap">
select * from student
</select>
<insert id="saveStudent" parameterType="list">
insert into student(name,sex,age)
<foreach collection="studentList" item="item" separator="," index="index">
(#{name},#{sex},#{age})
</foreach>
</insert>
</mapper>
6、编写service层
package com.example.service;
import com.example.pojo.Student;
import java.util.List;
public interface StudentService {
//查询全部学生信息
List<Student> selectAll();
//批量插入学生数据
int saveStudent(List<Student> studentList);
}
package com.example.service.impl;
import com.example.dao.StudentDao;
import com.example.pojo.Student;
import com.example.service.StudentService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
/**
* 类名:
* 创建时间:2021/12/16-15:15
* 功能:
*/
@Service
public class StudentServiceImpl implements StudentService {
@Resource
private StudentDao studentDao;
@Override
public List<Student> selectAll() {
return studentDao.selectAll();
}
@Override
public int saveStudent(List<Student> studentList) {
return studentDao.saveStudent(studentList);
}
}
7、编写controller层
package com.example.controller;
import com.alibaba.excel.EasyExcel;
import com.example.pojo.Student;
import com.example.service.StudentService;
import com.example.utils.ExcelListener;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.File;
import java.util.List;
@RestController
@RequestMapping("/easyexcel")
public class EasyExcelController {
@Resource
private StudentService service;
@RequestMapping("/selectList")
public List<Student> selectAll(){
return service.selectAll();
}
@PostMapping("/import")
public void impostExcel(String filename){
EasyExcel.read(filename, Student.class,new ExcelListener()).sheet().doRead();
}
@PostMapping("/download")
public void downloadExcel(MultipartFile file){
EasyExcel.write((File) file,Student.class).sheet("").doWrite(service.selectAll());
}
}
8、编写数据监听
package com.example.utils;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.example.pojo.Student;
import java.util.Map;
/**
* 类名:数据监听
*/
public class ExcelListener extends AnalysisEventListener<Student> {
//一行一行读取
@Override
public void invoke(Student data, AnalysisContext context) {
System.out.println("====开始读取一行数据====");
System.out.println("**" + data);
System.out.println();
}
//读取表头内容
@Override
public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
System.out.println("表头:" + headMap);
}
//读取完成之后
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
System.out.println("====数据读取完毕====");
}
}