我用的事IDEA,jdk版本是1.7.新建项目的时候这个地方的选择需要注意一下,springboot版本是1.5的,否则不支持1.7的jdk

pom.xml

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-data-jpa</artifactId>
  4. </dependency>
  5. <dependency>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-web</artifactId>
  8. </dependency>
  9. <dependency>
  10. <groupId>org.mybatis.spring.boot</groupId>
  11. <artifactId>mybatis-spring-boot-starter</artifactId>
  12. <version>1.3.2</version>
  13. </dependency>
  14. <dependency>
  15. <groupId>org.springframework.boot</groupId>
  16. <artifactId>spring-boot-starter-aop</artifactId>
  17. </dependency>
  18.  
  19. <dependency>
  20. <groupId>mysql</groupId>
  21. <artifactId>mysql-connector-java</artifactId>
  22. <scope>runtime</scope>
  23. </dependency>
  24. <dependency>
  25. <groupId>org.springframework.boot</groupId>
  26. <artifactId>spring-boot-starter-test</artifactId>
  27. <scope>test</scope>
  28. </dependency>
  29.  
  30. <!-- 数据库连接池 -->
  31. <dependency>
  32. <groupId>com.alibaba</groupId>
  33. <artifactId>druid</artifactId>
  34. <version>1.0.20</version>
  35. </dependency>

======================异常处理

ExceptionHandler.java

  1. package com.springbootmybatis.demo.exceptiion;
  2.  
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5. import org.springframework.web.bind.annotation.ControllerAdvice;
  6. import org.springframework.web.bind.annotation.ExceptionHandler;
  7. import org.springframework.web.bind.annotation.ResponseBody;
  8.  
  9. import java.util.HashMap;
  10. import java.util.Map;
  11.  
  12. /**
  13. * 异常处理类
  14. */
  15. @ControllerAdvice
  16. public class ExceptionHandle {
  17. private final static Logger logger= LoggerFactory.getLogger(ExceptionHandle.class);
  18. /**
  19. * 处理返回的Exception类型的异常
  20. * @param e
  21. * @return
  22. */
  23. @ResponseBody
  24. @ExceptionHandler(value = Exception.class)
  25. public Map<String,Object> handler(Exception e){
  26. Map<String,Object> map=new HashMap<String, Object>();
  27. if(e instanceof MyException){//自定义异常
  28. MyException me=(MyException)e;
  29. map.put("status",me.getStatus());
  30. map.put("msg",e.getMessage());
  31. }else{
  32. //logger.error("系统异常:{}",e);
  33. map.put("status",2);
  34. map.put("msg","程序异常");
  35. }
  36. return map;
  37. }
  38. }

MyException.java

  1. package com.springbootmybatis.demo.exceptiion;
  2.  
  3. public class MyException extends RuntimeException {
  4. private Integer status;
  5. public MyException(Integer status,String message) {
  6. super(message);
  7. this.status=status;
  8. }
  9.  
  10. public Integer getStatus() {
  11. return status;
  12. }
  13.  
  14. public void setStatus(Integer status) {
  15. this.status = status;
  16. }
  17. }

================AOP

HttpAspect.java

  1. package com.springbootmybatis.demo.aspect;
  2.  
  3. import org.aspectj.lang.JoinPoint;
  4. import org.aspectj.lang.annotation.After;
  5. import org.aspectj.lang.annotation.AfterReturning;
  6. import org.aspectj.lang.annotation.Aspect;
  7. import org.aspectj.lang.annotation.Before;
  8. import org.slf4j.Logger;
  9. import org.slf4j.LoggerFactory;
  10. import org.springframework.stereotype.Component;
  11. import org.springframework.web.context.request.RequestContextHolder;
  12. import org.springframework.web.context.request.ServletRequestAttributes;
  13.  
  14. import javax.servlet.http.HttpServletRequest;
  15.  
  16. /**
  17. * Aop基本示例
  18. */
  19. @Aspect
  20. @Component
  21. public class HttpAspect {
  22. private final static Logger logger= LoggerFactory.getLogger(HttpAspect.class);
  23.  
  24. /**
  25. * 方法执行之前,拦截单个方法
  26. */
  27. @Before("execution(public * com.springbootmybatis.demo.controller.TestBootController.getUser(..))")
  28. public void aopOneBeforeMethod(JoinPoint joinpoint){
  29. ServletRequestAttributes attributes= (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
  30. HttpServletRequest request=attributes.getRequest();
  31. //url
  32. logger.info("url={}",request.getRequestURL());
  33. //method
  34. logger.info("method={}",request.getMethod());
  35. //ip
  36. logger.info("ip={}", request.getRemoteAddr());
  37. //类方法
  38. logger.info("class_method={}",joinpoint.getSignature().getDeclaringTypeName()+"."+joinpoint.getSignature().getName());
  39. //参数
  40. logger.info("args={}",joinpoint.getArgs());
  41. System.out.println("请求了getUser方法-->前");
  42. }
  43. /**
  44. * 方法执行之前,拦截所有的方法
  45. */
  46. @Before("execution(public * com.springbootmybatis.demo.controller.TestBootController.*(..))")
  47. public void aopAllBeforeMethod(){
  48. System.out.println("执行了所有的方法拦截-->前");
  49. }
  50.  
  51. /**
  52. * 方法执行之后,拦截单个方法
  53. */
  54. @After("execution(public * com.springbootmybatis.demo.controller.TestBootController.getUser(..))")
  55. public void aopOneAfterMethod(){
  56. System.out.println("请求了getUser方法-->后");
  57. }
  58. /**
  59. * 方法执行之前,拦截所有的方法
  60. */
  61. @After("execution(public * com.springbootmybatis.demo.controller.TestBootController.*(..))")
  62. public void aopAllAfterMethod(){
  63. System.out.println("执行了所有的方法拦截-->后");
  64. }
  65.  
  66. }

HttpAspectNoRepeat.java

  1. package com.springbootmybatis.demo.aspect;
  2.  
  3. import org.aspectj.lang.annotation.*;
  4. import org.slf4j.Logger;
  5. import org.slf4j.LoggerFactory;
  6. import org.springframework.stereotype.Component;
  7.  
  8. /**
  9. * Aop基本示例,去除重复的拦截配置
  10. */
  11. @Aspect
  12. @Component
  13. public class HttpAspectNoRepeat {
  14.  
  15. private final static Logger logger= LoggerFactory.getLogger(HttpAspectNoRepeat.class);
  16.  
  17. @Pointcut("execution(public * com.springbootmybatis.demo.controller.TestBootController.getUser(..))")
  18. public void aopOne(){
  19.  
  20. }
  21. @Pointcut("execution(public * com.springbootmybatis.demo.controller.TestBootController.*(..))")
  22. public void aopAll(){
  23.  
  24. }
  25. /**
  26. * 方法执行之前,拦截单个方法
  27. */
  28. @Before("aopOne()")
  29. public void aopOneBeforeMethod(){
  30. logger.info("去除重复配置后的单个方法拦截-->前-->logger");
  31. }
  32. /**
  33. * 方法执行之前,拦截所有的方法
  34. */
  35. @Before("aopAll()")
  36. public void aopAllBeforeMethod(){
  37. System.out.println("去除重复配置后的所有方法拦截-->前");
  38. }
  39.  
  40. /**
  41. * 方法执行之后,拦截单个方法
  42. */
  43. @After("aopOne()")
  44. public void aopOneAfterMethod(){
  45. System.out.println("去除重复配置后的单个方法拦截-->后");
  46. }
  47. /**
  48. * 方法执行之前,拦截所有的方法
  49. */
  50. @After("aopAll()")
  51. public void aopAllAfterMethod(){
  52. System.out.println("去除重复配置后的所有方法拦截-->后");
  53. }
  54.  
  55. @AfterReturning(returning = "object",pointcut = "aopOne()")
  56. public void getReturnFromMethod(Object object){
  57. logger.info("返回值:{}",object);
  58. }
  59. }

TestBootController.java

  1. package com.springbootmybatis.demo.controller;
  2.  
  3. import com.springbootmybatis.demo.entity.Gys;
  4. import com.springbootmybatis.demo.exceptiion.MyException;
  5. import com.springbootmybatis.demo.service.GysServiceImpl;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.web.bind.annotation.RequestMapping;
  8. import org.springframework.web.bind.annotation.ResponseBody;
  9. import org.springframework.web.bind.annotation.RestController;
  10.  
  11. import javax.annotation.Resource;
  12. import java.util.HashMap;
  13. import java.util.List;
  14. import java.util.Map;
  15.  
  16. @RestController
  17. @RequestMapping("/testboot")
  18. public class TestBootController {
  19.  
  20. @RequestMapping("/getgys")
  21. public Gys getUser() {
  22. Gys user = new Gys();
  23. user.setRoleName("test");
  24. return user;
  25. }
  26.  
  27. @Autowired
  28. private GysServiceImpl gysService;
  29. @RequestMapping("/getlist")
  30. public List<Gys> getlist() {
  31. List<Gys> list=null;
  32. try {
  33. list=gysService.getGysList();
  34. }catch (Exception e){
  35. e.printStackTrace();
  36. }
  37. return list;
  38. }
  39.  
  40. @ResponseBody
  41. @RequestMapping("/testException")
  42. public Map<String,Object> testException() throws Exception {
  43. boolean a=false;
  44. if(a){
  45. return new HashMap<String, Object>();
  46. }else{
  47. int c=0;
  48. int v=5/c;
  49. return null;
  50. //throw new Exception("测试一个异常");
  51. }
  52. }
  53. @ResponseBody
  54. @RequestMapping("/testMyException")
  55. public Map<String,Object> testMyException() throws Exception {
  56. boolean a=false;
  57. if(a){
  58. return new HashMap<String, Object>();
  59. }else{
  60. throw new MyException(3,"测试一个自定义异常");
  61. }
  62. }
  63. }

ITestDao.java

  1. package com.springbootmybatis.demo.dao;
  2.  
  3. import com.springbootmybatis.demo.entity.Gys;
  4.  
  5. import java.util.List;
  6.  
  7. public interface IGysDao {
  8. List<Gys> getUserList() throws Exception;
  9. }

GysServiceImpl.java

  1. package com.springbootmybatis.demo.service;
  2.  
  3. import com.springbootmybatis.demo.dao.IGysDao;
  4. import com.springbootmybatis.demo.entity.Gys;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.stereotype.Service;
  7.  
  8. import javax.annotation.Resource;
  9. import java.util.List;
  10.  
  11. @Service("gysService")
  12. public class GysServiceImpl {
  13. @Autowired
  14. private IGysDao iGysDao;
  15.  
  16. public List<Gys> getGysList() throws Exception{
  17. return iGysDao.getUserList();
  18. }
  19. }

DemoApplication.java

  1. package com.springbootmybatis.demo;
  2.  
  3. import org.mybatis.spring.annotation.MapperScan;
  4. import org.springframework.boot.SpringApplication;
  5. import org.springframework.boot.autoconfigure.SpringBootApplication;
  6. import org.springframework.boot.web.support.SpringBootServletInitializer;
  7.  
  8. @SpringBootApplication
  9. @MapperScan("com.springbootmybatis.demo.dao")
  10. public class DemoApplication extends SpringBootServletInitializer{
  11.  
  12. public static void main(String[] args) {
  13. SpringApplication.run(DemoApplication.class, args);
  14. }
  15. }

Gys.java

  1. package com.springbootmybatis.demo.entity;
  2.  
  3. public class Gys {
  4. private String roleName;
  5.  
  6. public String getRoleName() {
  7. return roleName;
  8. }
  9.  
  10. public void setRoleName(String roleName) {
  11. this.roleName = roleName;
  12. }
  13. }

Gys.xml

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
  3. <mapper namespace="com.springbootmybatis.demo.dao.IGysDao">
  4. <select id="getUserList" resultType="com.springbootmybatis.demo.entity.Gys">
  5. SELECT * FROM gys;
  6. </select>
  7. </mapper>

application-dev.yml

  1. mybatis:
  2. mapper-locations: classpath:mapper/*.xml
  3. spring:
  4. datasource:
  5. driver-class-name: com.mysql.jdbc.Driver
  6. url: jdbc:mysql://localhost:3306/springmvc-mybatis
  7. username: root
  8. password: gys
  9. type: com.alibaba.druid.pool.DruidDataSource
  10. server:
  11. port: 8082
  12. logging:
  13. level: debug

application.yml

  1. spring:
  2. profiles:
  3. active: dev

 ===============单元测试(可以在需要测试的界面右击==>go to==>test...)

测试service

  1. package com.springbootmybatis.demo;
  2.  
  3. import com.springbootmybatis.demo.entity.Gys;
  4. import com.springbootmybatis.demo.service.GysServiceImpl;
  5. import org.junit.Assert;
  6. import org.junit.Test;
  7. import org.junit.runner.RunWith;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.boot.test.context.SpringBootTest;
  10. import org.springframework.test.context.junit4.SpringRunner;
  11.  
  12. import java.util.List;
  13.  
  14. /**
  15. * 测试service
  16. */
  17. @RunWith(SpringRunner.class)
  18. @SpringBootTest
  19. public class TestGysService {
  20.  
  21. @Autowired
  22. private GysServiceImpl gysService;
  23.  
  24. @Test
  25. public void getGysList() throws Exception{
  26. List<Gys> list=gysService.getGysList();
  27. Assert.assertEquals(2,list.size());
  28. }
  29. }

测试controller

  1. package com.springbootmybatis.demo.controller;
  2.  
  3. import org.junit.Test;
  4. import org.junit.runner.RunWith;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
  7. import org.springframework.boot.test.context.SpringBootTest;
  8. import org.springframework.test.context.junit4.SpringRunner;
  9. import org.springframework.test.web.servlet.MockMvc;
  10. import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
  11. import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
  12.  
  13. import static org.junit.Assert.*;
  14.  
  15. /**
  16. * 测试controller
  17. */
  18. @RunWith(SpringRunner.class)
  19. @SpringBootTest
  20. @AutoConfigureMockMvc
  21. public class TestBootControllerTest {
  22.  
  23. @Autowired
  24. private MockMvc mvc;
  25.  
  26. @Test
  27. public void getUser() throws Exception {
  28. mvc.perform(MockMvcRequestBuilders.get("/getgys"))
  29. .andExpect(MockMvcResultMatchers.status().isOk());
  30. }
  31.  
  32. }

springboot+mybatis整合(单元测试,异常处理,日志管理,AOP)的更多相关文章

  1. SpringBoot Mybatis整合(注解版),SpringBoot集成Mybatis(注解版)

    SpringBoot Mybatis整合(注解版),SpringBoot集成Mybatis(注解版) ================================ ©Copyright 蕃薯耀 2 ...

  2. SpringBoot | 第二十三章:日志管理之整合篇

    前言 在本系列<第四章:日志管理>中,由于工作中日志这块都是走默认配置,也没有深入了解过,因为部署过程中直接使用了linux中的输出重定向功能,如java -jar xx.jar > ...

  3. SpringBoot+Mybatis整合入门(一)

    SpringBoot+Mybatis 四步整合 第一步 添加依赖 springBoot+Mybatis相关依赖 <!--springBoot相关--> <parent> < ...

  4. Mybatis整合Spring实现事务管理的源码分析

    一:前言 没有完整看完,但是看到了一些关键的地方,这里做个记录,过程会有点乱,以后逐渐补充最终归档为完整流程:相信看过框架源码的都知道过程中无法完全确定是怎样的流程,毕竟不可能全部都去测试一遍 ,但是 ...

  5. springboot(整合多数据源demo,aop,定时任务,异步方法调用,以及获取properties中自定义的变量值)

    有这么一个需求 每个部门,需要操作的数据库不同,A部门要将数据放test数据库,B 部门数据 要放在test1数据库 同一个项目 需要整合 多个数据源 上传个demo 方便自己以后回看!!!!!!!! ...

  6. SpringBoot+Mybatis整合实例

    前言 大家都知道springboot有几大特点:能创建独立的Spring应用程序:能嵌入Tomcat,无需部署WAR文件:简化Maven配置:自动配置Spring等等.这里整合mybatis,创建一个 ...

  7. 2、SpringBoot+Mybatis整合------一对一

    开发工具:STS 代码下载链接:https://github.com/theIndoorTrain/SpringBoot_Mybatis01/tree/93398da60c647573645917b2 ...

  8. springboot mybatis 整合

    新建项目在上一篇. 第二步:创建表和相应的实体类 实体类:user.java package com.qtt.im.entity; import java.io.Serializable; publi ...

  9. springboot/Mybatis整合

    正题 本项目使用的环境: 开发工具:Intellij IDEA 2017.1.3 springboot: 1.5.6 jdk:1.8.0_161 maven:3.3.9 额外功能 PageHelper ...

随机推荐

  1. Percona Toolkit之pt-table-checksum学习

    pt-table-checksum用来检测主从数据库上的数据一致性,其原理是通过在主库上运行一系列的MySQL函数计算每个表的散列值,并利用主从关系将相同的操作在从服务器上重放(基于statement ...

  2. 新建 django 项目

    安装 django ,就不必多说,python 环境是 python 3.6,django 安装的命令为: pip3 install django==2.1.7 开始demo,名字为 guest dj ...

  3. day8 大纲

    01 昨日内容回顾 文件操作 文件操作的流程: 1,打开文件创建文件句柄. 2,对文件句柄进行操作. 3,关闭文件句柄. 读, r r+ rb r+b read() 全部读取 read(n) 读取一部 ...

  4. mysql之 误用SECONDS_BEHIND_MASTER衡量MYSQL主备的延迟时间

    链接:http://www.woqutech.com/?p=1116 MySQL 本身通过 show slave status 提供了 Seconds_Behind_Master ,用于衡量主备之间的 ...

  5. Linux 操作系统下,安装软件 apt-get、yum 的区别

    Linux 操作系统主要分为两大类: RedHat系列:Redhat.Centos.Fedora等: Debian系列:Debian.Ubuntu等. yum(Yellow dog Updater, ...

  6. Python应用场景 (转)

    Web应用开发 Python经常被用于Web开发.比如,通过mod_wsgi模块,Apache可以运行用Python编写的Web程序.Python定义了WSGI标准应用接口来协调Http服务器与基于P ...

  7. js-自定义对话框

    引用插件 <link rel="stylesheet" type="text/css" href="${ctx }/resources/comm ...

  8. hadoop append 追加文件错误

    java.io.IOException:Failed to replace a bad datanode on the existing pipeline due to no more good da ...

  9. Digispark红外接收器

    一.红外协议之NEC协议原理 NEC协议格式: 首次发送的是9ms的高电平脉冲,其后是4.5ms的低电平,接下来就是8bit的地址码(从低有效位开始发),而后是8bit的地址码的反码(主要是用于校验是 ...

  10. Python程序的执行过程 解释型语言和编译型语言

    转载地址:http://blog.csdn.net/lujiandong1/article/details/50067655 1. Python是一门解释型语言? 我初学Python时,听到的关于Py ...