zoukankan      html  css  js  c++  java
  • spring_aop_切面日志实现

    maven依赖包

    <!--AOP切面配置 -->
    <dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjrt</artifactId>
    <version>1.8.6</version>
    </dependency>
    <dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.8.6</version>
    </dependency>
    <dependency>
    <groupId>aopalliance</groupId>
    <artifactId>aopalliance</artifactId>
    <version>1.0</version>
    </dependency>
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aspects</artifactId>
    <version>${spring.version}</version>
    </dependency>
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aop</artifactId>
    <version>${spring.version}</version>
    </dependency>

    springMVC.xml配置

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:aop="http://www.springframework.org/schema/aop"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:mvc="http://www.springframework.org/schema/mvc"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xsi:schemaLocation="http://www.springframework.org/schema/beans 
             http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context 
            http://www.springframework.org/schema/context/spring-context-4.3.xsd
            http://www.springframework.org/schema/mvc 
            http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
            http://www.springframework.org/schema/aop 
            http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
            http://www.springframework.org/schema/tx 
            http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
    
        <!-- 自动扫描包 -->
        <context:component-scan
            base-package="com.mis.yxnz.controller"></context:component-scan>
            
        <!--扫描AOP包 -->
        <context:component-scan base-package="com.mis.yxnz.common"></context:component-scan>
     
        <!-- AOP 代理开启 -->
        <aop:aspectj-autoproxy expose-proxy="true"></aop:aspectj-autoproxy>
    
        <!-- 视图解析器 -->
        <bean id="viewResolver"
            class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <!-- <property name="prefix" value="WEB-INF/views/"></property> -->
            <property name="prefix" value="page/"></property>
            <property name="suffix" value=".jsp"></property>
        </bean>
         <mvc:default-servlet-handler />
        <mvc:annotation-driven></mvc:annotation-driven>
        <!-- 配置transactionManager事务管理器 -->
        <bean id="transactionManager"
            class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="dataSource"></property>
        </bean>
    
        <!-- 配置事物通知属性 -->
        <tx:advice id="txAdvice"
            transaction-manager="transactionManager">
            <!-- 定义事物传播特性 -->
            <tx:attributes>
                <tx:method name="insert*" propagation="REQUIRED" />
                <tx:method name="update*" propagation="REQUIRED" />
                <tx:method name="edit*" propagation="REQUIRED" />
                <tx:method name="save*" propagation="REQUIRED" />
                <tx:method name="add*" propagation="REQUIRED" />
                <tx:method name="new*" propagation="REQUIRED" />
                <tx:method name="set*" propagation="REQUIRED" />
                <tx:method name="remove*" propagation="REQUIRED" />
                <tx:method name="delete*" propagation="REQUIRED" />
                <tx:method name="change*" propagation="REQUIRED" />
                <tx:method name="check*" propagation="REQUIRED" />
                <tx:method name="get*" propagation="REQUIRED" />
                <tx:method name="find*" propagation="REQUIRED" />
                <tx:method name="load*" propagation="REQUIRED" />
                <tx:method name="*" propagation="REQUIRED" />
            </tx:attributes>
        </tx:advice>
        <!-- 配置事物切面 -->
        <aop:config>
            <aop:pointcut id="serviceOperation"
                expression="execution(* com.mis.yxnz.service.*.*(..))" />
            <aop:advisor advice-ref="txAdvice"
                pointcut-ref="serviceOperation" />
        </aop:config>
       
        <!--避免IE执行AJAX时,返回JSON出现下载文件 -->
        <bean id="mappingJacksonHttpMessageConverter"
            class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <property name="supportedMediaTypes">
                <list>
                    <value>text/html;charset=UTF-8</value>
                    <value>application/json;charset=UTF-8</value>
                </list>
            </property>
        </bean>
        <!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 -->
        <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
            <property name="messageConverters">
                <list>
                    <ref bean="mappingJacksonHttpMessageConverter" /> <!-- JSON转换器 -->
                </list>
            </property>
        </bean>
        <!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 -->
        <bean id="multipartResolver"
            class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
            <!-- 默认编码 -->
            <property name="defaultEncoding" value="utf-8" />
            <!-- 文件大小最大值 -->
            <property name="maxUploadSize" value="10485760000" />
            <!-- 内存中的最大值 -->
            <property name="maxInMemorySize" value="40960" />
        </bean>
        <!-- 静态资源处理 css js imgs -->
        <mvc:resources location="/resources/**"
            mapping="/resources" />
        <mvc:annotation-driven>
            <!-- 消息转换器,解决responseBody返回中外乱码问题 -->
            <mvc:message-converters
                register-defaults="true">
                <bean
                    class="org.springframework.http.converter.StringHttpMessageConverter">
                    <property name="supportedMediaTypes"
                        value="text/plain;charset=UTF-8" />
                </bean>
            </mvc:message-converters>
        </mvc:annotation-driven>
        <mvc:annotation-driven />
        <!-- 拦截器 -->
        <mvc:interceptors>
            <mvc:interceptor>
                <!-- /**表示所有url包括子url路径 -->
                <mvc:mapping path="/**" />
                <bean class="com.mis.yxnz.util.HandlerInterceptor" />
            </mvc:interceptor>
        </mvc:interceptors>
        <mvc:resources location="/" mapping="/**/*.css" />
        <mvc:resources location="/" mapping="/**/*.js" />
    </beans>

    公共类

    package com.mis.yxnz.common.annotation;

    import java.lang.annotation.Documented;
    import java.lang.annotation.ElementType;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;
    
    /**
     * @category ——初始化自定义注解 SysLogT  默认参数""
     * <p>Description: 系统日志注解</p>    
     * @author LiQian  
     * @date 2018年10月8日  
     * @version 3.0  
     */
    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface SysLogT {
        String value() default "";
    }
    


    package com.mis.yxnz.common.aspect; import java.lang.reflect.Method; import java.text.SimpleDateFormat; import java.util.Date; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.google.gson.Gson; import com.mis.yxnz.common.annotation.SysLogT; import com.mis.yxnz.entity.XtglOperationLog; import com.mis.yxnz.service.XtglOperationLogService; import com.mis.yxnz.util.HttpContextUtils; import com.mis.yxnz.util.IPUtils; import net.sf.json.JSONObject; /** * <p> * Description: 系统日志,切面处理类 * </p> * * @author LiQian * @date 2018年10月8日 * @version 3.0 */ @Aspect @Component public class SysLogAspect { @Autowired private HttpServletRequest request; @Autowired private XtglOperationLogService xtglOperationLogService; //@Pointcut("") public SysLogAspect() { System.out.println("********"); // super(); } @Around("execution(* com.mis.yxnz.controller.*.*.*(..))&&@annotation(log)") public Object around(ProceedingJoinPoint point, SysLogT log) throws Throwable { System.out.println("*********************around*************************"); long beginTime = System.currentTimeMillis(); Object result = point.proceed(); long time = System.currentTimeMillis() - beginTime; boolean m = true; // 回调方法 保存日志 saveSysLog(point, time,result); return result; } private void saveSysLog(ProceedingJoinPoint joinPoint, long time,Object result) { try { HttpServletRequest request = HttpContextUtils.getHttpServletRequest(); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); MethodSignature signature = (MethodSignature) joinPoint.getSignature(); Method method = signature.getMethod(); JSONObject object = JSONObject.fromObject(result); String msg=object.getString("msg"); System.out.println("执行情况:" + msg); String menth= joinPoint.getTarget().getClass().getName()+"."+signature.getName()+"()"; System.out.println("请求方法:" + menth); SysLogT syslog = method.getAnnotation(SysLogT.class); XtglOperationLog log = new XtglOperationLog(); HttpSession session = request.getSession(); Object[] args = joinPoint.getArgs(); String params = new Gson().toJson(args[0]); System.out.println("请求参数:"+params); log.setOperationPersonnel(session.getAttribute("userName").toString());// 操作人员 log.setOperationName(syslog.value());// 操作 log.setOperationParameter(params);// 执行参数 log.setOperationCondition(menth);// 执行方法 log.setOperationTime(df.format(new Date()));// 执行时间 log.setOperationIp(IPUtils.getIpAddr(request));// 执行ip log.setOperationExpendTime(Long.toString(time));// 执行耗时 log.setOperationStatus(msg);// 执行情况 log.setOperation_organization_id(Integer.parseInt(session.getAttribute("organization_id").toString()));// 机构外键 xtglOperationLogService.insertSelective(log); } catch (Exception e) { System.out.println("日志记录出错!"); } } }

    方法注解,实现记录日志

    @SysLogT("删除角色")
    @RequestMapping(value = "roleDel", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public R roleDel(@RequestParam("ids") String roleId) {
    Integer orgId = Integer.parseInt(CheckSession.GetOrgId(request));
    xtglRoleService.deleteByBatch(roleId.split(","));
    return R.ok();
    }

     
  • 相关阅读:
    循环的中断
    创建.NET应用程序所经历的步骤
    完整的开发一个ContentProvider步骤
    Perl 基于OOP的数据库链接(增删改查)
    Perl 基于OOP的数据库链接(优化)
    Perl 基于OOP的数据库链接
    Perl oop链接数据库
    Perl oop研究
    PythonStudy——内存管理机制 Memory management mechanism
    博客园美化——Design by Venti
  • 原文地址:https://www.cnblogs.com/lq2020/p/13500682.html
Copyright © 2011-2022 走看看