导入依赖 pom.xml
<dependencies>
<!-- web依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--TKmybatis插件通用mapper-->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>2.1.2</version>
</dependency>
<!--spring整合mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
<!--mysql依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
<version>5.1.47</version>
</dependency>
<!--使用阿里巴巴的druid数据源,有利于监控sql的执行情况-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<!--lombat-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
</dependency>
<!--添加swagger2依赖的jar包-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
<!--druid连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.18</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.18</version>
</dependency>
</dependencies>
1. 配置文件
application.properties
指定DAO包,可以在日志上输出运行时的sql语句
logging.level.com.tina.gymboree.gymuser.dao=debug
application.yml
#指定激活那个配置文件
spring:
profiles:
active: dev
application-dev.yml
#mybatis批量给包起别名
mybatis:
type-aliases-package: com.tina.gymboree.gymuser.dao
#指定端口
server:
port: 8001
#配置mysql数据源
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://152.136.27.48:3306/d_tina?characterEncoding=utf8&characterSetResults=utf8&autoReconnect=true&failOverReadOnly=false
username: root
password: 123456
# 指定druid连接池
type: com.alibaba.druid.pool.DruidDataSource
#配置druid的其他属性
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
#配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,wall
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
2.实体类
package com.tina.gymboree.gymuser.entity;
import lombok.Data;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @program: gym-user
* @description
* @author: tina.liu
* @create: 2020-01-21 12:39
**/
@Data
@Table(name = "t_employee")
public class Employee{
@Id
private String id;
private String empName;
private String empSalary;
private String empAge;
}
3. DAO层
package com.tina.gymboree.gymuser.dao;
import com.tina.gymboree.gymuser.entity.Employee;
import org.apache.ibatis.annotations.Mapper;
/**
* @program: gym-user
* @description
* @author: tina.liu
* @create: 2020-01-21 12:41
**/
@Mapper
public interface EmployeeDao extends tk.mybatis.mapper.common.Mapper<Employee> {
}
4.service 层
package com.tina.gymboree.gymuser.service;
import com.tina.gymboree.gymuser.exceptionHandler.EntityResp;
/**
* @program: gym-user
* @description
* @author: tina.liu
* @create: 2020-01-21 12:44
**/
public interface EmployeeService {
EntityResp<Object> getUserById(String id);
}
package com.tina.gymboree.gymuser.service.impl;
import com.tina.gymboree.gymuser.dao.EmployeeDao;
import com.tina.gymboree.gymuser.entity.Employee;
import com.tina.gymboree.gymuser.exceptionHandler.Code;
import com.tina.gymboree.gymuser.exceptionHandler.EntityResp;
import com.tina.gymboree.gymuser.service.EmployeeServie;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
/**
* @program: gym-user
* @description
* @author: tina.liu
* @create: 2020-01-21 13:16
**/
@Service
public class EmployeeServiceImpl implements EmployeeService {
@Resource
private EmployeeDao employeeDao;
@Override
public EntityResp<Object> getUserById(String id) {
Employee employeeSelectConditon = new Employee();
int i=3/0;
employeeSelectConditon.setId(id);
List<Employee> result = employeeDao.select(employeeSelectConditon);
return new EntityResp<>(result, Code.SERVER_SUCCESS);
}
}//类的大括号
5. controller层
TestController
package com.tina.gymboree.gymuser.controller;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @program: gym-user
* @description
* @author: tina.liu
* @create: 2020-01-21 13:26
**/
@RestController
@Api(value = "test模块")
@RequestMapping("/test")
public class TestController {
@GetMapping("/demo")
@ApiOperation(value = "测试get的方法")
public Object demo(){
return "测试get成功~~";
}
}
EmployeeController
package com.tina.gymboree.gymuser.controller;
import com.tina.gymboree.gymuser.exceptionHandler.EntityResp;
import com.tina.gymboree.gymuser.service.EmployeeServie;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @program: gym-user
* @description
* @author: tina.liu
* @create: 2020-01-21 13:12
**/
@RestController
@RequestMapping(value = "/employee")
public class EmployeeController {
@Autowired
private EmployeeService employeeService;
@GetMapping(value = "getUserById")
public EntityResp<Object> getUserById(String id){
return employeeService.getUserById(id);
}
}
6. config
DruidConfig
package com.tina.gymboree.gymuser.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* @program: gym-user
* @description
* @author: tina.liu
* @create: 2020-01-21 13:40
**/
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druid(){
return new DruidDataSource();
}
//配置Druid的监控
//1、配置一个管理后台的Servlet
@Bean
public ServletRegistrationBean statViewServlet(){
ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
Map<String,String> initParams = new HashMap<>();
initParams.put("loginUsername","admin");
initParams.put("loginPassword","123456");
initParams.put("allow","");//默认就是允许所有访问
initParams.put("deny","127.0.0.1");
bean.setInitParameters(initParams);
return bean;
}
//2、配置一个web监控的filter
@Bean
public FilterRegistrationBean webStatFilter(){
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
Map<String,String> initParams = new HashMap<>();
initParams.put("exclusions","*.js,*.css,/druid/*");
bean.setInitParameters(initParams);
bean.setUrlPatterns(Arrays.asList("/*"));
return bean;
}
}//类的大括号
SwaggerConfig
package com.tina.gymboree.gymuser.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.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
/**
* @program: gym-user
* @description
* @author: tina.liu
* @create: 2020-01-21 13:25
**/
@Configuration //表明是一个配置类
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("测试接口文档")
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.tina.gymboree.gymuser.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("springboot利用swagger构建api文档")
.description("简单优雅的restful风格,http://blog.csdn.net/saytime")
.termsOfServiceUrl("http://blog.csdn.net/saytime")
.version("1.0")
.build();
}
}
7. 工具类
CreatedId
package com.tina.gymboree.gymuser.util;
import java.util.UUID;
/**
* @program: gym-user
* @description
* @author: tina.liu
* @create: 2020-01-21 14:40
* 利用UUID随机生成一个32的数字作为ID
**/
public class CreatedId {
public static String getUUID(){
UUID uuid= UUID.randomUUID();
String str = uuid.toString();
String uuidStr=str.replace("-", "");
return uuidStr;
}
}
CreatedTime
package com.tina.gymboree.gymuser.util;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @program: gym-user
* @description
* @author: tina.liu
* @create: 2020-01-21 14:42
**/
public class CreatedTime {
public static String getTime(){
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
}
}
memberNotNull
package com.tina.gymboree.gymuser.util;
import java.lang.reflect.Field;
/**
* @program: gym-user
* @description
* @author: tina.liu
* @create: 2020-01-21 14:44
**/
public class memberNotNull {
//静态的方法
public static void checkEntityValuesNull(Object object,String... args) throws Exception {
if(args.length ==0) {
throw new RuntimeException("参数不能为空");
}
//获取class对象
Class clazz = object.getClass();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
//判断是否传参数
for(String arg:args) {
if(field.getName().equals(arg) ) {
if(field.get(object) == null) {
throw new RuntimeException(arg+"不能为空");
}
}
}
}
}
/**
* 测试的例子:
* public static void main(String[] args) throws Exception {
* Employee employee = new Employee();
* employee.setId("1");
* employee.setEmpName("tina");
* employee.setEmpSalary("120000");
* EntityUtil.checkEntityValuesNull(employee,"id", "empName","empSalary");
* }
*/
}//类的大括号
8. 全局捕获异常工具类
Code
package com.tina.gymboree.gymuser.exceptionHandler;
import lombok.Data;
/**
* @program: gym-user
* @description
* @author: tina.liu
* @create: 2020-01-21 14:24
**/
public enum Code {
SERVER_OTHER_ERROR ("500","服务器异常"),//枚举类如果写方法的话,此处需要写分号
SERVER_SUCCESS ("200","SUCCESS");
private String ecode;
private String emsg;
Code(String ecode, String emsg) {
this.ecode = ecode;
this.emsg = emsg;
}
public String getEcode() {
return ecode;
}
public String getEmsg() {
return emsg;
}
public static Code statOf(String ecode) {
for (Code state : values())
if (state.getEcode().equals(ecode))
return state;
return null;
}
@Data
public static class DemoException {
private String code;
private String errMsg;
}
}
EntityResp
package com.tina.gymboree.gymuser.exceptionHandler;
import lombok.Data;
/**
* @program: gym-user
* @description
* @author: tina.liu
* @create: 2020-01-21 14:25
**/
@Data
public class EntityResp<T> {
private T data;
private String status;
private String message;
public EntityResp() {
}
public EntityResp(T t, Code code){
this.data = t;
this.status = code.getEcode();
this.message =code.getEmsg();
}
public EntityResp(Code code){
this.data = null;
this.status = code.getEcode();
this.message =code.getEmsg();
}
}
MyExceptionHandler
package com.tina.gymboree.gymuser.exceptionHandler;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @program: gym-user
* @description
* @author: tina.liu
* @create: 2020-01-21 14:26
**/
@ControllerAdvice
public class MyExceptionHandler {
@ExceptionHandler(value =Exception.class)
@ResponseBody
public EntityResp<String> exceptionHandler(Exception e){
return new EntityResp<>(e.getMessage(), Code.SERVER_OTHER_ERROR);
}
}
8 启动类
GymUserApplication
package com.tina.gymboree.gymuser;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@SpringBootApplication
@EnableSwagger2 //启动swagger
public class GymUserApplication {
public static void main(String[] args) {
SpringApplication.run(GymUserApplication.class, args);
}
}