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;css

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();
}html

相關文章
相關標籤/搜索