springboot2.3.1 spring-aop5.2.7 非侵入式,实现控制层切面,记录访问日志

1. SysLogAspect定义切面类

package com.shok.aop;

import com.shok.Constants.Constants;
import com.shok.model.User;
import com.shok.utils.FileUtils;
import com.shok.utils.IpUtils;
import com.shok.utils.JsonUtils;
import com.shok.utils.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 声明一个切面,用来记录请求日志
 */
@Aspect
@Component
public class SysLogAspect {

    /**
     * 切入点表达式,将control层加入执行范围
     */
    @Pointcut("execution(* com.shok.web..*.*(..))")
    public void logPointCut() {

    }

    /**
     * 环绕通知 @Around
     * @param point
     * @return
     * @throws Throwable
     */
    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        // 开始执行时间
        long beginTime = System.currentTimeMillis();
        // 执行返回结果
        Object result = point.proceed();
        // 请求执行时间,毫秒值
        long time = System.currentTimeMillis() - beginTime;
        try {
            // 写日志
            saveLog(point, result, time);
        } catch (Exception e) {
        }
        return result;
    }

    /**
     * 保存日志
     * @param joinPoint 接入点
     * @param result    请求执行返回json结果
     * @param time      请求执行时间
     */
    private void saveLog(ProceedingJoinPoint joinPoint, Object result, long time) {
        Map<String, Object> map = new HashMap();
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();
        User user = (User) request.getSession().getAttribute(Constants.CURRENT_USER);
        map.put("userName", user.getUserName());
        String get_post = request.getMethod();
        map.put("get_post", get_post);

        String ip = IpUtils.getClientIpAddress(request);
        map.put("ip", ip);

        String uri = request.getRequestURI();
        map.put("uri", uri);

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        // 获取包名、类名
        String className = signature.getDeclaringTypeName();
        map.put("className", className);
        // 获取方法名
        String methodName = signature.getName();
        map.put("methodName", methodName);

        //
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String reqTime = dateFormat.format(new Date());
        map.put("reqTime", reqTime);

        //请求的参数
        Object[] args = joinPoint.getArgs();
        List<String> list = new ArrayList<String>();
        try {
            String tmp = "";
            int i = 0;
            for (Object o : args) {
                i++;
                tmp = JsonUtils.toJSONString(o);
                tmp = StringUtils.replaceBlankmark(tmp);
                list.add(tmp);
                if (i == 1) {
                    map.put("parm", tmp);
                } else {
                    map.put("parm" + i, tmp);
                }
            }
        } catch (Exception e) {
        }
        map.put("reqTime", reqTime);
        map.put("execTime", time);
        map.put("result", result);
        System.out.println("==result==" + result);
        String json = JsonUtils.toJSONString(map);
        System.out.println("==json==" + json);
        // 记录日志
        FileUtils.wmsLogAppend(json);
    }
}

2.控制层,StoreController

package com.shok.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.shok.mapper.StoreMapper;
import com.shok.model.Store;
import com.shok.model.User;
import com.shok.utils.JsonUtils;
import com.shok.Constants.ResultCode;
import com.shok.utils.ResultGenerator;
import com.shok.utils.ResultResponse;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@RestController
public class StoreController {

    @Autowired
    private StoreMapper storeMapper;
    @Autowired
    ResultGenerator resultGenerator;

    @ApiOperation("入库操作,609该库存已存在,不能重复入库;610入库成功;611入库失败 {\"partNo\":\"零件号\",\"containerId\":\"箱号\",\"stockLocation\":\"库位地址\",\"quantity\":入库数量,\"remark\":\"入库备注\"}")
    @RequestMapping(value = "/inStore", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public ResultResponse inStore(@RequestBody String json, HttpServletRequest request) throws JsonProcessingException {
        Store store = JsonUtils.toObject(json, Store.class);
        SimplePropertyPreFilter filter = new SimplePropertyPreFilter(Store.class, "partNo", "containerId", "stockLocation", "quantity", "remark");
        String cn_json = JSON.toJSONString(store, filter);
        Map map = JsonUtils.toMap(cn_json);
        // 查询是否已经入库
        int cnt = storeMapper.findInStore(map);
        if (cnt > 0) {
            return resultGenerator.getSuccessResult(ResultCode.EXIST_INSTORE);
        }

        User user = (User) request.getSession().getAttribute("USER");
        map.put("inboundOperator", user.getUserName());
        // 入库操作
        cnt = storeMapper.inStore(map);
        if (cnt == 1) {
            return resultGenerator.getSuccessResult(ResultCode.YES_INSTORE);
        } else {
            return resultGenerator.getSuccessResult(ResultCode.NO_INSTORE);
        }
    }

    @ApiOperation("出库操作,606出库成功、607出库失败;608货物已出库,不能重复出库;615货物不存在 {\"partNo\":\"零件号\",\"containerId\":\"箱号\"}")
    @RequestMapping(value = "/outStore", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public ResultResponse outStore(@RequestBody String json, HttpServletRequest request) {
        Store store = JsonUtils.toObject(json, Store.class);
        SimplePropertyPreFilter filter = new SimplePropertyPreFilter(Store.class, "partNo", "containerId");
        String cn_json = JSON.toJSONString(store, filter);

        Map map = JsonUtils.toMap(cn_json);

        // 查询是否已经入库
        int cnt = storeMapper.findInStore(map);
        // 货物不存在,也就是未入库
        if (cnt == 0) {
            return resultGenerator.getSuccessResult(ResultCode.EXIST_STORE);
        }

        // 出库检查
        cnt = storeMapper.findOutStore(map);
        // 货物已出库,不能重复出库
        if (cnt == 0) {
            return resultGenerator.getSuccessResult(ResultCode.EXIST_OUTSTORE);
        }

        User user = (User) request.getSession().getAttribute("USER");
        map.put("outboundOperator", user.getUserName());

        // 货物存在,进行出库操作
        cnt = storeMapper.outStore(map);
        if (cnt == 1) {
            return resultGenerator.getSuccessResult(ResultCode.YES_OUTSTORE);
        } else {
            return resultGenerator.getSuccessResult(ResultCode.NO_OUTSTORE);
        }
    }
    /**
     * 返回JSONArray
     *
     * @param json
     * @return
     */
    @ApiOperation("出库前,扫码零件号,根据零件号查询库存是否存在,605零件号存在,604零件号不存在")
    @RequestMapping(value = "/getCountByPartNo", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public ResultResponse getCountByContainerId(@RequestBody String json, HttpServletRequest request) {
        Store store = JsonUtils.toObject(json, Store.class);
        SimplePropertyPreFilter filter = new SimplePropertyPreFilter(Store.class, "partNo");
        String cn_json = JSON.toJSONString(store, filter);
        Map map = JsonUtils.toMap(cn_json);
        int cnt = storeMapper.getCountByPartNo(map);
        if (cnt > 0) {
            return resultGenerator.getSuccessResult(ResultCode.YES_partNo);
        } else {
            return resultGenerator.getSuccessResult(ResultCode.NO_partNo);
        }
    }

    @ApiOperation("出库前,扫码箱号,根据零件号和箱号查询库存,601箱号不存在、602该箱号已经出库、603返回库存数据")
    @RequestMapping(value = "/findByContainerId", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public ResultResponse findByContainerId(@RequestBody String json, HttpServletRequest request) {
        Store store = JsonUtils.toObject(json, Store.class);
        SimplePropertyPreFilter filter = new SimplePropertyPreFilter(Store.class, "partNo", "containerId");
        String cn_json = JSON.toJSONString(store, filter);
        Map map = JsonUtils.toMap(cn_json);

        // 根据零件号,查询库存
        Store store2 = storeMapper.findByContainerId(map);
        if (store2 == null) {
            return resultGenerator.getSuccessResult(ResultCode.NO_CONTAINERID);
        } else if (store2.getOutboundTime() != null) {
            return resultGenerator.getSuccessResult(ResultCode.OUT_CONTAINERID);
        } else {
            // 查询入库记录
            filter = new SimplePropertyPreFilter(Store.class, "partNo", "containerId", "stockLocation", "quantity", "remark", "inboundTime", "inboundOperator");
            return resultGenerator.getSuccessResult(ResultCode.DATA_CONTAINERID, JsonUtils.toObject(JSON.toJSONString(store, filter)));
        }
    }

    @ApiOperation("出库前,根据零件号,查询货物详细记录!603返回库存数据")
    @RequestMapping(value = "/findByPartNo/{partNo}", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public ResultResponse findByPartNo(@PathVariable("partNo") String partNo, HttpServletRequest request) {
        // 根据零件号,查询库存,
        List<Store> ls = storeMapper.findByPartNo(partNo);
        SimplePropertyPreFilter filter = new SimplePropertyPreFilter(Store.class, "containerId", "stockLocation", "quantity", "remark", "inboundTime", "inboundOperator", "outboundTime", "outboundOperator");
        return resultGenerator.getSuccessResult(ResultCode.DATA_CONTAINERID, JsonUtils.toObject(JSONObject.toJSONString(ls, filter)));
    }
}

3.pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.shok</groupId>
    <artifactId>wms</artifactId>
    <version>1.0.0</version>
    <packaging>jar</packaging>

    <name>wms</name>
    <description>scan code wms</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <!--        <finalName>wms</finalName>&lt;!&ndash; war or jar 包的名称 &ndash;&gt;-->
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <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>2.1.3</version>
        </dependency>

        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>2.10.6</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.72</version>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-spring-webmvc</artifactId>
            <version>2.10.5</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.10.5</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.10.5</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.5</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.module</groupId>
            <artifactId>jackson-module-jaxb-annotations</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.2.2</version>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>eu.bitwalker</groupId>
            <artifactId>UserAgentUtils</artifactId>
            <version>1.21</version>
        </dependency>


        <!--        aop start -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.9.5</version>
        </dependency>

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.5</version>
        </dependency>


        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>3.3.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>5.2.7.RELEASE</version>
        </dependency>
        <!--        aop end -->

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

4.FileUtils文件处理工具类

package com.shok.utils;

import com.shok.Constants.Constants;
import org.joda.time.DateTime;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class FileUtils {

    public static void main(String[] args) {
        String fp1 = "E:\\data\\logs\\202007\\wms20200709.log";
        create_path_file(fp1);
    }

    public static void wmsLogAppend(String content){
        DateTime dateTime = new DateTime();
        String yd = dateTime.toString("yyyyMM");
        String date = dateTime.toString("yyyyMMdd");
        String fileName = Constants.LOGS_PATH + yd +"/"+  Constants.LOGS_PREFIX + date + Constants.LOGS_SUFFIX;
        appendFile(fileName,content);
    }

    /**
     * 根据目标文件,创建他的父目录,不过文件不存在,就创建文件
     *
     * @param destPathFile 目录+文件名
     * @return
     */
    public static boolean create_path_file(String destPathFile) {
        File file = new File(destPathFile);
        File fileParent = file.getParentFile();

        // 目录不存在,则创建目录
        if (!fileParent.exists()) {
            fileParent.mkdirs();
        }

        // 文件不存在,则创建文件
        if (!file.exists()) {
            try {
                return file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return true;
    }

    /**
     * 将内容追加到文件末尾
     * @param pathFileName 文件路径+文件名
     * @param content  追加的内容
     */
    public static void appendFile(String pathFileName, String content) {
        // 创建目录和文件
        create_path_file(pathFileName);
        try {
            // 打开一个随机访问文件流,按读写方式
            RandomAccessFile randomFile = new RandomAccessFile(pathFileName, "rw");
            // 文件长度,字节数
            long fileLength = randomFile.length();
            // 将写文件指针移到文件尾
            randomFile.seek(fileLength);
            // 防止中文乱码
            randomFile.write((content + System.getProperty("line.separator")).getBytes());
            randomFile.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'deptServiceImpl': Unsatisfied dependency expressed through field 'baseMapper'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'deptMapper' defined in file [D:\WorkSpace\work13\djd_server\target\classes\com\jiading\djd\mapper\DeptMapper.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: org.apache.ibatis.builder.BuilderException: Error creating document instance. Cause: org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 40; 元素内容必须由格正确的字符数据或标记组成。 at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:643) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE] at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:130) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1422) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:594) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:226) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE] at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:893) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE] at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:879) ~[spring-context-5.2.7.RELEASE.jar:5.2.7.RELEASE] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:551) ~[spring-context-5.2.7.RELEASE.jar:5.2.7.RELEASE] at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:143) ~[spring-boot-2.3.1.RELEASE.jar:2.3.1.RELEASE] at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:758) [spring-boot-2.3.1.RELEASE.jar:2.3.1.RELEASE] at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:750) [spring-boot-2.3.1.RELEASE.jar:2.3.1.RELEASE] at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) [spring-boot-2.3.1.RELEASE.jar:2.3.1.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-2.3.1.RELEASE.jar:2.3.1.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1237) [spring-boot-2.3.1.RELEASE.jar:2.3.1.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) [spring-boot-2.3.1.RELEASE.jar:2.3.1.RELEASE] at com.jiading.djd.DjdApplication.main(DjdApplication.java:14) [classes/:na]报错了
07-25
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

sdcxlgb

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值