综合案例
前言:
- 本案例会应用到ssm、SpringBoot技术和Lombok、Swagger工具以及RESTFuI风格;并且会大概讲述一下SpringBoot、Lombok和Swagger。
一、SpringBoot
1.1 概述:
- 什么是SpringBoot?
- 用来简化新Spring应用的初始搭建以及开发过程 。
- 特点:
- 维护依赖,解决jar冲突。提供众多启动器(相当于jar包集合)
- 简化配置,大大减少了配置文件、配置类。
- 默认实现,默认情况下,提供了众多解决方案。
1.2 入门案例:
- 创建maven项目
- pom.xml文件中添加web开发启动器
- 编写controller,基于RESTFuI风格
- 编写启动类
1.2.1 实现
- 创建maven项目 : day01_springboot
- pom.xml文件中添加web开发启动器
<!--确定spring boot版本-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.5.RELEASE</version>
<relativePath/>
</parent>
<dependencies>
<!--web开发启动器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
- 编写controller,基于RESTFuI风格
package com.czxy.demo01.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @Author: 小新
* @Date: 2021-12-16 10:35
*/
/*@Controller
@ResponseBody*/
@RestController
public class HelloController {
@RequestMapping("/hello")
public String hello(){
return "hello word!";
}
}
- 编写启动类
package com.czxy.demo01;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Day01SpringbootApplication {
public static void main(String[] args) {
SpringApplication.run(Day01SpringbootApplication.class, args);
}
}
二、Lombok
2.1 概述:
- 什么是Lombok?
- Lombok是一个简化JavaBean编写的工具。使用注解去掉了JavaBean中的getter/setter方法、toString方法、构造方法等。
2.2 使用
2.2.1 搭建环境
- IDEA配置:shift + ctrl + alt + / 快捷键选择 Register
- 安装Lombok插件
- 添加坐标
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
- 使用
package com.czxy.domain;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
/**
* @Author: 小新
* @Date: 2021-12-28 09:53
*/
@Data // @Setter、@Getter、@ToString
@AllArgsConstructor //全参构造
@NoArgsConstructor //无参构造
public class Person {
private String userName;
private String password;
private String age;
private Date birthday;
}
2.3 总结
注解 | 描述 |
---|---|
@Data | 自动生成getter、setter、toString等方法 |
@Setter | 自动生成setter方法 |
@Getter | 自动生成getter方法 |
@ToString | 自动生成toString方法 |
@AllArgsConstructor | 全参构造 |
@NoArgsConstructor | 无参构造 |
三、Swagger
3.1 概述:
- 什么是Swagger?
- API自动生成工具
3.2 使用
3.2.1搭建环境
- 步骤 :
- 导入坐标
- cope配置类
- 特定注解
- 实现 :
- 导入坐标
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<swagger.version>2.7.0</swagger.version>
</properties>
<dependencies>
<!--swagger2-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
</dependency>
</dependencies>
- cope配置类 :Swagger2ConfigurationV3
package com.czxy.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.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
import java.util.List;
/**
* Swagger2 配置类,
* 访问路径:swagger-ui.html
* 自动注册:
* 位置:resources/META-INF/spring.factories
* 内容:
* org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
* com.czxy.config.Swagger2Configuration
*/
@Configuration
@EnableSwagger2
public class Swagger2ConfigurationV3 {
@Bean
public Docket createRestApi() {
// 1 确定文档Swagger版本
Docket docket = new Docket(DocumentationType.SWAGGER_2);
// 2 设置 api基本信息
docket.apiInfo(apiInfo());
// 3 设置自定义加载路径
docket = docket.select()
.apis(RequestHandlerSelectors.basePackage("com.czxy"))
.paths(PathSelectors.any())
.build();
//4 设置权限
docket.securitySchemes(securitySchemes());
docket.securityContexts(securityContexts());
return docket;
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("API")
.description("基于swagger接口文档")
.contact(new Contact("xxx","联系方式"))
.version("1.0")
.build();
}
private List<ApiKey> securitySchemes() {
List<ApiKey> list = new ArrayList<>();
// name 为参数名 keyname是页面传值显示的 keyname, name在swagger鉴权中使用
list.add(new ApiKey("Authorization", "Authorization", "header"));
return list;
}
private List<SecurityContext> securityContexts() {
List<SecurityContext> list = new ArrayList<>();
list.add(SecurityContext.builder()
.securityReferences(defaultAuth())
.forPaths(PathSelectors.regex("^(?!auth).*$"))
.build());
return list;
}
private List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
List<SecurityReference> list = new ArrayList();
list.add(new SecurityReference("Authorization", authorizationScopes));
return list;
}
}
- 访问
http://localhost:8080/swagger-ui.html
- 特定注解
注解 | 描述 |
---|---|
@Api | 修饰整个类,描述Controller的作用 |
@ApiOperation | 描述一个类的一个方法,或者说一个接口 |
@ApiParam | 单个参数描述 |
@ApiModel | 用对象来接收参数 |
@ApiModelPropertyr | 用对象接收参数时,描述对象的一个字段 |
@ApiResponse | HTTP响应其中1个描述 |
@ApiResponses | HTTP响应整体描述 |
@ApiIgnore | 使用该注解忽略这个API |
@ApiError | 发生错误返回的信息 |
@ApiImplicitParam | 一个请求参数 |
@ApiImplicitParams | 多个请求参数 |
四、SpringBoot + RESTFuI风格——增删改查
4.1 搭建环境
- 创建项目:day10_springboot
- 导入坐标
- 拷贝Swagger 配置类
- 编写application.yml文件
- 编写主程序类 day10Application
4.2 实现
- 创建项目:day10_springboot
- 导入坐标
<!-- 1 确定spring boot的版本-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.5.RELEASE</version>
</parent>
<!--2 确定版本-->
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<spring-cloud-release.version>Hoxton.SR3</spring-cloud-release.version>
<nacos.version>1.1.0</nacos.version>
<alibaba.cloud.version>2.2.1.RELEASE</alibaba.cloud.version>
<mybatis.starter.version>1.3.2</mybatis.starter.version>
<mapper.starter.version>2.0.2</mapper.starter.version>
<pageHelper.starter.version>1.2.5</pageHelper.starter.version>
<mysql.version>5.1.32</mysql.version>
<durid.starter.version>1.1.10</durid.starter.version>
<mybatis.plus.version>3.4.0</mybatis.plus.version>
<swagger.version>2.7.0</swagger.version>
<jwt.jjwt.version>0.9.0</jwt.jjwt.version>
<jwt.joda.version>2.9.7</jwt.joda.version>
<beanutils.version>1.9.3</beanutils.version>
</properties>
<!-- 3 添加依赖 -->
<dependencies>
<!--web开发启动器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--测试启动器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<!-- mybatis启动器 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>${mybatis.starter.version}</version>
</dependency>
<!-- 通用Mapper启动器 -->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>${mapper.starter.version}</version>
</dependency>
<!-- 分页助手启动器 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>${pageHelper.starter.version}</version>
</dependency>
<!-- mysql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!-- Druid连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>${durid.starter.version}</version>
</dependency>
<!--swagger2-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
- 拷贝Swagger 配置类
- 编写application.yml文件
spring:
datasource:
url: jdbc:mysql://localhost:3306/db_20211028
username: root
password: 1234
driver-class-name: com.mysql.jdbc.Driver
- 编写主程序类 day10Application
package com.czxy;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @Author: 小新
* @Date: 2021-12-27 09:00
*/
@SpringBootApplication
public class day10Application {
public static void main(String[] args) {
SpringApplication.run(day10Application.class,args);
}
}
4.3 增删改查功能
- 步骤:
- 编写domain (User)
- 编写mapper (UserMapper)
- 编写service (UserService)
- 编写service的实现类 (UserServiceImpl)
- 编写controller (UserController)
- 实现
- 编写domain (User)
package com.czxy.domain;
import org.springframework.format.annotation.DateTimeFormat;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Date;
/**
* @Author: 小新
* @Date: 2021-12-28 19:54
*/
@Data
@Table(name = "user")
public class User {
@Id
private String uid;
private String username;
private String password;
private String name;
private String email;
private String telephone;
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date birthday;
private String sex;
private Integer state;
private String code;
- 编写mapper (UserMapper)
package com.czxy.mapper;
import com.czxy.domain.User;
import tk.mybatis.mapper.common.Mapper;
/**
* @Author: 小新
* @Date: 2021-12-27 14:35
*/
@org.apache.ibatis.annotations.Mapper
public interface UserMapper extends Mapper<User> {
}
- 编写service (UserService)
package com.czxy.service;
import com.czxy.domain.User;
import java.util.List;
/**
* @Author: 小新
* @Date: 2021-12-27 14:36
*/
public interface UserService {
/**
* 查询所有
* @return
*/
List<User> selectAll();
/**
* 根据id查询详情
* @param uid
* @return
*/
User selectById(String uid);
/**
* 根据id删除
* @param uid
* @return
*/
Boolean delete(String uid);
/**
* 更新
* @param user
* @return
*/
Boolean update(User user);
/**
* 添加
* @param user
* @return
*/
Boolean add(User user);
}
- 编写service的实现类 (UserServiceImpl)
package com.czxy.service.impl;
import com.czxy.domain.User;
import com.czxy.mapper.UserMapper;
import com.czxy.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;
/**
* @Author: 小新
* @Date: 2021-12-27 14:39
*/
@Service
@Transactional
public class UserServiceImpl implements UserService {
@Resource
private UserMapper userMapper;
@Override
public List<User> selectAll() {
return userMapper.selectAll();
}
@Override
public User selectById(String uid) {
return userMapper.selectByPrimaryKey(uid);
}
@Override
public Boolean delete(String uid) {
int delete = userMapper.deleteByPrimaryKey(uid);
return delete == 1 ;
}
@Override
public Boolean update(User user) {
int update = userMapper.updateByPrimaryKey(user);
return update == 1 ;
}
@Override
public Boolean add(User user) {
int insert = userMapper.insertSelective(user);
return insert == 1 ;
}
}
- 编写controller (UserController)
package com.czxy.controller;
import com.czxy.domain.User;
import com.czxy.service.UserService;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
/**
* @Author: 小新
* @Date: 2021-12-27 14:46
*/
@RestController
@RequestMapping("/user")
public class UserController {
@Resource
private UserService userService;
/**
* 查询所有
* get
* @return
*/
@GetMapping
public List<User> selectAll(){
System.out.println("selectAll----success");
return userService.selectAll();
}
/**
* 根据id查询详情
* @param uid
* @return
*/
@GetMapping("/{id}")
public User selectAll(@PathVariable("id") String uid){
System.out.println("selectById:" + uid);
System.out.println("selectById----success");
return userService.selectById(uid);
}
/**
* 添加
* post
* @param user
* @return
*/
@PostMapping
public String insert(@RequestBody User user){
System.out.println("insert----");
Boolean result = userService.add(user);
if (result){
return "insert----success";
}else{
return "insert----error";
}
}
/**
* 更新
* put
* @param user
* @return
*/
@PutMapping
public String update(@RequestBody User user){
System.out.println("更新成功:" + user);
Boolean update = userService.update(user);
if (update){
return "update----success";
}else{
return "update----error";
}
}
/**
* 删除
* delete
* @param uid
* @return
*/
@DeleteMapping("/{id}")
public String delete(@PathVariable("id") String uid){
System.out.println("删除:" + uid);
Boolean delete = userService.delete(uid);
if (delete){
return "delete----success";
}else{
return "delete----error";
}
}
}
- 结果展示
- 查询所有
- 方法都可以实现,小编就不一 一展示了,避免给各位大老爷带来视觉疲惫。