springboot+mybatis整合(单元测试,异常处理,日志管理,AOP)
我用的事IDEA,jdk版本是1.7.新建项目的时候这个地方的选择需要注意一下,springboot版本是1.5的,否则不支持1.7的jdk
pom.xml
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-data-jpa</artifactId>
- </dependency>
- <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>1.3.2</version>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-aop</artifactId>
- </dependency>
- <dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- <scope>runtime</scope>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-test</artifactId>
- <scope>test</scope>
- </dependency>
- <!-- 数据库连接池 -->
- <dependency>
- <groupId>com.alibaba</groupId>
- <artifactId>druid</artifactId>
- <version>1.0.20</version>
- </dependency>
======================异常处理
ExceptionHandler.java
- package com.springbootmybatis.demo.exceptiion;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.web.bind.annotation.ControllerAdvice;
- import org.springframework.web.bind.annotation.ExceptionHandler;
- import org.springframework.web.bind.annotation.ResponseBody;
- import java.util.HashMap;
- import java.util.Map;
- /**
- * 异常处理类
- */
- @ControllerAdvice
- public class ExceptionHandle {
- private final static Logger logger= LoggerFactory.getLogger(ExceptionHandle.class);
- /**
- * 处理返回的Exception类型的异常
- * @param e
- * @return
- */
- @ResponseBody
- @ExceptionHandler(value = Exception.class)
- public Map<String,Object> handler(Exception e){
- Map<String,Object> map=new HashMap<String, Object>();
- if(e instanceof MyException){//自定义异常
- MyException me=(MyException)e;
- map.put("status",me.getStatus());
- map.put("msg",e.getMessage());
- }else{
- //logger.error("系统异常:{}",e);
- map.put("status",2);
- map.put("msg","程序异常");
- }
- return map;
- }
- }
MyException.java
- package com.springbootmybatis.demo.exceptiion;
- public class MyException extends RuntimeException {
- private Integer status;
- public MyException(Integer status,String message) {
- super(message);
- this.status=status;
- }
- public Integer getStatus() {
- return status;
- }
- public void setStatus(Integer status) {
- this.status = status;
- }
- }
================AOP
HttpAspect.java
- package com.springbootmybatis.demo.aspect;
- import org.aspectj.lang.JoinPoint;
- import org.aspectj.lang.annotation.After;
- import org.aspectj.lang.annotation.AfterReturning;
- import org.aspectj.lang.annotation.Aspect;
- import org.aspectj.lang.annotation.Before;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.stereotype.Component;
- import org.springframework.web.context.request.RequestContextHolder;
- import org.springframework.web.context.request.ServletRequestAttributes;
- import javax.servlet.http.HttpServletRequest;
- /**
- * Aop基本示例
- */
- @Aspect
- @Component
- public class HttpAspect {
- private final static Logger logger= LoggerFactory.getLogger(HttpAspect.class);
- /**
- * 方法执行之前,拦截单个方法
- */
- @Before("execution(public * com.springbootmybatis.demo.controller.TestBootController.getUser(..))")
- public void aopOneBeforeMethod(JoinPoint joinpoint){
- ServletRequestAttributes attributes= (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
- HttpServletRequest request=attributes.getRequest();
- //url
- logger.info("url={}",request.getRequestURL());
- //method
- logger.info("method={}",request.getMethod());
- //ip
- logger.info("ip={}", request.getRemoteAddr());
- //类方法
- logger.info("class_method={}",joinpoint.getSignature().getDeclaringTypeName()+"."+joinpoint.getSignature().getName());
- //参数
- logger.info("args={}",joinpoint.getArgs());
- System.out.println("请求了getUser方法-->前");
- }
- /**
- * 方法执行之前,拦截所有的方法
- */
- @Before("execution(public * com.springbootmybatis.demo.controller.TestBootController.*(..))")
- public void aopAllBeforeMethod(){
- System.out.println("执行了所有的方法拦截-->前");
- }
- /**
- * 方法执行之后,拦截单个方法
- */
- @After("execution(public * com.springbootmybatis.demo.controller.TestBootController.getUser(..))")
- public void aopOneAfterMethod(){
- System.out.println("请求了getUser方法-->后");
- }
- /**
- * 方法执行之前,拦截所有的方法
- */
- @After("execution(public * com.springbootmybatis.demo.controller.TestBootController.*(..))")
- public void aopAllAfterMethod(){
- System.out.println("执行了所有的方法拦截-->后");
- }
- }
HttpAspectNoRepeat.java
- package com.springbootmybatis.demo.aspect;
- import org.aspectj.lang.annotation.*;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.stereotype.Component;
- /**
- * Aop基本示例,去除重复的拦截配置
- */
- @Aspect
- @Component
- public class HttpAspectNoRepeat {
- private final static Logger logger= LoggerFactory.getLogger(HttpAspectNoRepeat.class);
- @Pointcut("execution(public * com.springbootmybatis.demo.controller.TestBootController.getUser(..))")
- public void aopOne(){
- }
- @Pointcut("execution(public * com.springbootmybatis.demo.controller.TestBootController.*(..))")
- public void aopAll(){
- }
- /**
- * 方法执行之前,拦截单个方法
- */
- @Before("aopOne()")
- public void aopOneBeforeMethod(){
- logger.info("去除重复配置后的单个方法拦截-->前-->logger");
- }
- /**
- * 方法执行之前,拦截所有的方法
- */
- @Before("aopAll()")
- public void aopAllBeforeMethod(){
- System.out.println("去除重复配置后的所有方法拦截-->前");
- }
- /**
- * 方法执行之后,拦截单个方法
- */
- @After("aopOne()")
- public void aopOneAfterMethod(){
- System.out.println("去除重复配置后的单个方法拦截-->后");
- }
- /**
- * 方法执行之前,拦截所有的方法
- */
- @After("aopAll()")
- public void aopAllAfterMethod(){
- System.out.println("去除重复配置后的所有方法拦截-->后");
- }
- @AfterReturning(returning = "object",pointcut = "aopOne()")
- public void getReturnFromMethod(Object object){
- logger.info("返回值:{}",object);
- }
- }
TestBootController.java
- package com.springbootmybatis.demo.controller;
- import com.springbootmybatis.demo.entity.Gys;
- import com.springbootmybatis.demo.exceptiion.MyException;
- import com.springbootmybatis.demo.service.GysServiceImpl;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.ResponseBody;
- import org.springframework.web.bind.annotation.RestController;
- import javax.annotation.Resource;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- @RestController
- @RequestMapping("/testboot")
- public class TestBootController {
- @RequestMapping("/getgys")
- public Gys getUser() {
- Gys user = new Gys();
- user.setRoleName("test");
- return user;
- }
- @Autowired
- private GysServiceImpl gysService;
- @RequestMapping("/getlist")
- public List<Gys> getlist() {
- List<Gys> list=null;
- try {
- list=gysService.getGysList();
- }catch (Exception e){
- e.printStackTrace();
- }
- return list;
- }
- @ResponseBody
- @RequestMapping("/testException")
- public Map<String,Object> testException() throws Exception {
- boolean a=false;
- if(a){
- return new HashMap<String, Object>();
- }else{
- int c=0;
- int v=5/c;
- return null;
- //throw new Exception("测试一个异常");
- }
- }
- @ResponseBody
- @RequestMapping("/testMyException")
- public Map<String,Object> testMyException() throws Exception {
- boolean a=false;
- if(a){
- return new HashMap<String, Object>();
- }else{
- throw new MyException(3,"测试一个自定义异常");
- }
- }
- }
ITestDao.java
- package com.springbootmybatis.demo.dao;
- import com.springbootmybatis.demo.entity.Gys;
- import java.util.List;
- public interface IGysDao {
- List<Gys> getUserList() throws Exception;
- }
GysServiceImpl.java
- package com.springbootmybatis.demo.service;
- import com.springbootmybatis.demo.dao.IGysDao;
- import com.springbootmybatis.demo.entity.Gys;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Service;
- import javax.annotation.Resource;
- import java.util.List;
- @Service("gysService")
- public class GysServiceImpl {
- @Autowired
- private IGysDao iGysDao;
- public List<Gys> getGysList() throws Exception{
- return iGysDao.getUserList();
- }
- }
DemoApplication.java
- package com.springbootmybatis.demo;
- import org.mybatis.spring.annotation.MapperScan;
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
- import org.springframework.boot.web.support.SpringBootServletInitializer;
- @SpringBootApplication
- @MapperScan("com.springbootmybatis.demo.dao")
- public class DemoApplication extends SpringBootServletInitializer{
- public static void main(String[] args) {
- SpringApplication.run(DemoApplication.class, args);
- }
- }
Gys.java
- package com.springbootmybatis.demo.entity;
- public class Gys {
- private String roleName;
- public String getRoleName() {
- return roleName;
- }
- public void setRoleName(String roleName) {
- this.roleName = roleName;
- }
- }
Gys.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.springbootmybatis.demo.dao.IGysDao">
- <select id="getUserList" resultType="com.springbootmybatis.demo.entity.Gys">
- SELECT * FROM gys;
- </select>
- </mapper>
application-dev.yml
- mybatis:
- mapper-locations: classpath:mapper/*.xml
- spring:
- datasource:
- driver-class-name: com.mysql.jdbc.Driver
- url: jdbc:mysql://localhost:3306/springmvc-mybatis
- username: root
- password: gys
- type: com.alibaba.druid.pool.DruidDataSource
- server:
- port: 8082
- logging:
- level: debug
application.yml
- spring:
- profiles:
- active: dev
===============单元测试(可以在需要测试的界面右击==>go to==>test...)
测试service
- package com.springbootmybatis.demo;
- import com.springbootmybatis.demo.entity.Gys;
- import com.springbootmybatis.demo.service.GysServiceImpl;
- import org.junit.Assert;
- 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.test.context.junit4.SpringRunner;
- import java.util.List;
- /**
- * 测试service
- */
- @RunWith(SpringRunner.class)
- @SpringBootTest
- public class TestGysService {
- @Autowired
- private GysServiceImpl gysService;
- @Test
- public void getGysList() throws Exception{
- List<Gys> list=gysService.getGysList();
- Assert.assertEquals(2,list.size());
- }
- }
测试controller
- package com.springbootmybatis.demo.controller;
- import org.junit.Test;
- import org.junit.runner.RunWith;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
- import org.springframework.boot.test.context.SpringBootTest;
- import org.springframework.test.context.junit4.SpringRunner;
- import org.springframework.test.web.servlet.MockMvc;
- import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
- import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
- import static org.junit.Assert.*;
- /**
- * 测试controller
- */
- @RunWith(SpringRunner.class)
- @SpringBootTest
- @AutoConfigureMockMvc
- public class TestBootControllerTest {
- @Autowired
- private MockMvc mvc;
- @Test
- public void getUser() throws Exception {
- mvc.perform(MockMvcRequestBuilders.get("/getgys"))
- .andExpect(MockMvcResultMatchers.status().isOk());
- }
- }
springboot+mybatis整合(单元测试,异常处理,日志管理,AOP)的更多相关文章
- SpringBoot Mybatis整合(注解版),SpringBoot集成Mybatis(注解版)
SpringBoot Mybatis整合(注解版),SpringBoot集成Mybatis(注解版) ================================ ©Copyright 蕃薯耀 2 ...
- SpringBoot | 第二十三章:日志管理之整合篇
前言 在本系列<第四章:日志管理>中,由于工作中日志这块都是走默认配置,也没有深入了解过,因为部署过程中直接使用了linux中的输出重定向功能,如java -jar xx.jar > ...
- SpringBoot+Mybatis整合入门(一)
SpringBoot+Mybatis 四步整合 第一步 添加依赖 springBoot+Mybatis相关依赖 <!--springBoot相关--> <parent> < ...
- Mybatis整合Spring实现事务管理的源码分析
一:前言 没有完整看完,但是看到了一些关键的地方,这里做个记录,过程会有点乱,以后逐渐补充最终归档为完整流程:相信看过框架源码的都知道过程中无法完全确定是怎样的流程,毕竟不可能全部都去测试一遍 ,但是 ...
- springboot(整合多数据源demo,aop,定时任务,异步方法调用,以及获取properties中自定义的变量值)
有这么一个需求 每个部门,需要操作的数据库不同,A部门要将数据放test数据库,B 部门数据 要放在test1数据库 同一个项目 需要整合 多个数据源 上传个demo 方便自己以后回看!!!!!!!! ...
- SpringBoot+Mybatis整合实例
前言 大家都知道springboot有几大特点:能创建独立的Spring应用程序:能嵌入Tomcat,无需部署WAR文件:简化Maven配置:自动配置Spring等等.这里整合mybatis,创建一个 ...
- 2、SpringBoot+Mybatis整合------一对一
开发工具:STS 代码下载链接:https://github.com/theIndoorTrain/SpringBoot_Mybatis01/tree/93398da60c647573645917b2 ...
- springboot mybatis 整合
新建项目在上一篇. 第二步:创建表和相应的实体类 实体类:user.java package com.qtt.im.entity; import java.io.Serializable; publi ...
- springboot/Mybatis整合
正题 本项目使用的环境: 开发工具:Intellij IDEA 2017.1.3 springboot: 1.5.6 jdk:1.8.0_161 maven:3.3.9 额外功能 PageHelper ...
随机推荐
- Percona Toolkit之pt-table-checksum学习
pt-table-checksum用来检测主从数据库上的数据一致性,其原理是通过在主库上运行一系列的MySQL函数计算每个表的散列值,并利用主从关系将相同的操作在从服务器上重放(基于statement ...
- 新建 django 项目
安装 django ,就不必多说,python 环境是 python 3.6,django 安装的命令为: pip3 install django==2.1.7 开始demo,名字为 guest dj ...
- day8 大纲
01 昨日内容回顾 文件操作 文件操作的流程: 1,打开文件创建文件句柄. 2,对文件句柄进行操作. 3,关闭文件句柄. 读, r r+ rb r+b read() 全部读取 read(n) 读取一部 ...
- mysql之 误用SECONDS_BEHIND_MASTER衡量MYSQL主备的延迟时间
链接:http://www.woqutech.com/?p=1116 MySQL 本身通过 show slave status 提供了 Seconds_Behind_Master ,用于衡量主备之间的 ...
- Linux 操作系统下,安装软件 apt-get、yum 的区别
Linux 操作系统主要分为两大类: RedHat系列:Redhat.Centos.Fedora等: Debian系列:Debian.Ubuntu等. yum(Yellow dog Updater, ...
- Python应用场景 (转)
Web应用开发 Python经常被用于Web开发.比如,通过mod_wsgi模块,Apache可以运行用Python编写的Web程序.Python定义了WSGI标准应用接口来协调Http服务器与基于P ...
- js-自定义对话框
引用插件 <link rel="stylesheet" type="text/css" href="${ctx }/resources/comm ...
- hadoop append 追加文件错误
java.io.IOException:Failed to replace a bad datanode on the existing pipeline due to no more good da ...
- Digispark红外接收器
一.红外协议之NEC协议原理 NEC协议格式: 首次发送的是9ms的高电平脉冲,其后是4.5ms的低电平,接下来就是8bit的地址码(从低有效位开始发),而后是8bit的地址码的反码(主要是用于校验是 ...
- Python程序的执行过程 解释型语言和编译型语言
转载地址:http://blog.csdn.net/lujiandong1/article/details/50067655 1. Python是一门解释型语言? 我初学Python时,听到的关于Py ...