新建项目跟着idea一步一步来,选择依赖的时候记得要选 Spring Web
项目创建成功看下pom
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.mybatis.spring.bootgroupId>
<artifactId>mybatis-spring-boot-starterartifactId>
<version>2.1.4version>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-devtoolsartifactId>
<scope>runtimescope>
<optional>trueoptional>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<scope>runtimescope>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
dependencies>
修改application.properties为application.yml,添加如下代码
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/你的数据库名称? useUnicode=true&characterEncoding=utf8&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=GMT%2B8&allowMultiQueries=true
username: root
password: 你的密码
driver-class-name: com.mysql.cj.jdbc.Driver
config: 一些配置
controller: 请求入口
mapper:查询方法的接口包(一般都是用工具生成)
pojo:对象模型
po是数据库映射来的
vo各种请求或者返回)
result : 封装接口统一返回的数据
service : 业务层
utils: 常用工具方法丢这里
resource下的mapper存放xml文件。
idea创建项目时已经引入了mybatis的依赖,还需要在yml中配置下mybatis扫描的包
mybatis:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.project.work.pojo.po
在pom中引入依赖
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-redisartifactId>
dependency>
redis:
database: 0
host: 127.0.0.1
port: 6379
# password: 123456
pool:
min-idle: 1 # 连接池中的最小空闲连接
max-idle: 300 # 连接池中的最大空闲连接
maxActive: 600 # 连接池最大连接数(使用负值表示没有限制)
maxWait: 10 # 连接池最大阻塞等待时间(使用负值表示没有限制)
timeout: 1000 # 连接超时时间(毫秒)
pom中添加依赖
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-apiartifactId>
<version>1.7.30version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-log4j12artifactId>
<version>1.7.30version>
dependency>
在resource下新建logback.xml
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<contextName>logback-democontextName>
<property name="log.charset" value="UTF-8"/>
<property name="log.pattern" value="[%date][%level][%thread][%class:%line] - %msg%n"/>
<property name="logdir" value="./logs">property>
<appender name="consoleLog" class="ch.qos.logback.core.ConsoleAppender">
<encoder charset="${log.charset}">
<pattern>${log.pattern}pattern>
encoder>
appender>
<appender name="fileInfoLog" class="ch.qos.logback.core.rolling.RollingFileAppender">
<File>${logdir}/demo.logFile>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<FileNamePattern>${logdir}/log.%d{yyyy-MM-dd}.%i.logFileNamePattern>
<maxHistory>30maxHistory>
<totalSizeCap>1GBtotalSizeCap>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>20MBmaxFileSize>
timeBasedFileNamingAndTriggeringPolicy>
rollingPolicy>
<encoder>
<charset>UTF-8charset>
<pattern>%d [%thread] %-5level %logger{36} %line - %msg%npattern>
encoder>
appender>
<root level="INFO">
<appender-ref ref="consoleLog"/>
<appender-ref ref="fileInfoLog"/>
root>
<logger name="com.project.demo" level="INFO" additivity="false">
<appender-ref ref="consoleLog"/>
<appender-ref ref="fileInfoLog"/>
logger>
configuration>
yml中增加日志配置
logging:
config: classpath:logback.xml
level:
com.hl.magic: trace
pom添加依赖
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-aopartifactId>
dependency>
在config包下新建类AopConfig
package com.project.demo.config;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
@Aspect
@Configuration
public class AopConfig {
private static Logger logger = LoggerFactory.getLogger(AopConfig.class);
/**
* 切入点
*/
@Pointcut("execution(* com.project.demo.controller.TestController.*(..)) ")
public void executionService() {}
/**
* 方法调用之前调用
*
* @param joinPoint
*/
@Before(value = "executionService()")
public void doBefore(JoinPoint joinPoint) {
logger.info("Before");
}
/**
* 方法之后调用
*
* @param joinPoint
* @param returnValue 方法返回值
*/
@AfterReturning(pointcut = "executionService()", returning = "returnValue")
public void doAfterReturning(JoinPoint joinPoint, Object returnValue) {
logger.info("AfterReturning");
}
/**
* 统计方法执行耗时Around环绕通知
*
* @param joinPoint
* @return
*/
@Around("executionService()")
public Object timeAround(ProceedingJoinPoint joinPoint) {
Object obj = null;
try {
obj = joinPoint.proceed();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
logger.info("Around");
return obj;
}
}
在config下新建WebMvcConfig
package com.project.demo.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* Spring MVC 配置
*/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
//解决跨域问题
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedHeaders("*")
.allowedMethods("*")
.allowedOrigins("*");
}
//添加拦截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
}
}
在result包中建立三个class
Result、ResultCode、ResultGenerator
Result
package com.project.demo.result;
import io.swagger.annotations.ApiModel;
/**
* 统一API响应结果封装
*/
@ApiModel
public class Result<T> {
private int code;
private String message;
private T data;
public Result setCode(ResultCode resultCode) {
this.code = resultCode.code();
this.message = resultCode.tips();
return this;
}
public int getCode() {
return code;
}
public String getMessage() {
return message;
}
public Result setMessage(String message) {
this.message = message;
return this;
}
public T getData() {
return data;
}
public Result setData(T data) {
this.data = data;
return this;
}
}
ResultCode
package com.project.demo.result;
/**
* 响应码枚举,参考HTTP状态码的语义
*/
public enum ResultCode {
SUCCESS(200,"Success"),//成功
FAIL(400,"Failure"),//失败
UNAUTHORIZED(401,"Unauthorized"),//未认证(签名错误)
NOT_FOUND(404,"Not Found");//接口不存在
private final int code;
private final String tips;
ResultCode(int code,String tips) {
this.code = code;
this.tips = tips;
}
public int code() {
return code;
}
public String tips() {
return tips;
}
}
ResultGenerator
package com.project.demo.result;
/**
* 响应结果生成工具
*/
public class ResultGenerator {
private static final String DEFAULT_SUCCESS_MESSAGE = "SUCCESS";
public static Result genSuccessResult() {
return new Result()
.setCode(ResultCode.SUCCESS)
.setMessage(DEFAULT_SUCCESS_MESSAGE);
}
public static <T> Result<T> genSuccessResult(T data) {
return new Result()
.setCode(ResultCode.SUCCESS)
.setData(data);
}
public static Result genFailResult(String message) {
return new Result()
.setCode(ResultCode.FAIL)
.setData(message);
}
public static Result genFailUnauthorized(String message) {
return new Result()
.setCode(ResultCode.UNAUTHORIZED)
.setData(message);
}
}
在pom中添加
<dependency>
<groupId>io.springfoxgroupId>
<artifactId>springfox-boot-starterartifactId>
<version>3.0.0version>
dependency>
在config包下新建SwaggerConfig.java
package com.project.work.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.oas.annotations.EnableOpenApi;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
@Configuration
@EnableOpenApi
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.OAS_30)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.project.demo.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("基于Swagger3.0.0的接口文档")
.description("api信息列表")
.version("0.01")
.contact(new Contact("", "", ""))
.build();
}
}
在controller包下新建个TestController测试下
package com.project.demo.controller;
import com.project.demo.result.Result;
import com.project.demo.result.ResultGenerator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
@Api("测试")
@RestController
@RequestMapping("/test")
public class TestController {
private static final Logger logger = LoggerFactory.getLogger(TestController.class);
@Resource
private RedisTemplate<String, String> redisTemplate;
@ApiOperation(value = "测试接口")
@ApiResponses(@ApiResponse(code = 200, message = "处理成功"))
@RequestMapping(value = "testget", method = RequestMethod.GET)
public Result<String> testGetRequest(String name, String age){
logger.debug("=====>测试日志debug级别打印<====");
logger.info("=====>测试日志info级别打印<=====");
logger.error("=====>测试日志error级别打印<====");
logger.warn("=====>测试日志warn级别打印<=====");
redisTemplate.opsForValue().set("test", "1122312");
return ResultGenerator.genSuccessResult(redisTemplate.opsForValue().get("test"));
}
@RequestMapping(value = "testpost", method = RequestMethod.POST)
public String testPostRequest(){
return "456";
}
}