自定义注解简单使用

 简单使用自定义注解,记录对数据库增删的操作信息。

1.创建注解

package com.test.util;
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;
@Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented
public @interface Log { /** 操作描述 */ String desc() default "";//这里暂且定义一个属性
  /**属性类型个数没有限制*/ }

 

2.切面类

package com.test.util;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.reflect.CodeSignature;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.guodu.pojo.Auth;
import com.guodu.pojo.LogOper;
import com.guodu.service.impl.LogOperServiceImpl;

/**
 * @author Administrator
 * @Description 日志记录
 */
public class LogAspect {
    @Autowired
    private LogOperServiceImpl logOperServiceImpl;
    
    private long startTimeMillis = 0; // 开始时间  
    private long endTimeMillis = 0; // 结束时间  
    private HttpServletRequest request = null;//请求
   /**
    * @param joinPoint
    * @Description 前质通知  方法调用前触发   记录开始时间,从session中获取操作人
    */
    public void before(JoinPoint joinPoint){  
        startTimeMillis = System.currentTimeMillis(); 
    } 
    /**
     * @param joinPoint
     * @Description 获取入参方法参数
     * @return
     */
    public Map<String, Object> getNameAndValue(JoinPoint joinPoint) {
        Map<String, Object> param = new HashMap<String, Object>();
        Object[] paramValues = joinPoint.getArgs();//获取切入方法的所有参数,任意类型
        String[] paramNames = ((CodeSignature)joinPoint.getSignature()).getParameterNames();//获取参数名称
        for (int i = 0; i < paramNames.length; i++) {
                param.put(paramNames[i], paramValues[i]);
        }
        return param;
    }
    /**目标方法执行后执行
     * @param joinPoint
     * @Description
     */
    public void after(JoinPoint joinPoint, Object returnVal) {
        request = getHttpServletRequest();
        String targetName = joinPoint.getTarget().getClass().getName(); //所属类名
        String methodName = joinPoint.getSignature().getName();  //目标方法名
        Object[] arguments = joinPoint.getArgs(); //目标方法参数
        Class<?> targetClass = null;
        try {
            targetClass = Class.forName(targetName);//反射得到目标方法所在类对象实例
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        Method[] methods = targetClass.getMethods();//获得该类的所有方法
        String desc;
        Class<?>[] clazzs;
        for (Method method : methods) {  //遍历所有方法
            if (method.getName().equals(methodName)) {  //判断是否为当前目标方法
                clazzs = method.getParameterTypes();  //返回目标方法参数类型数组
                if (clazzs!=null&&clazzs.length == arguments.length //判断长度是否与上面获取的参数个数相等,防止方法重载时方法名相同参数列表不同
                &&method.getAnnotation(Log.class)!=null) { //判断目标方法是否添加@Log注解 
                    desc = method.getAnnotation(Log.class).desc();//获取目标方法的Log注解的desc属性值
                    endTimeMillis = System.currentTimeMillis();

              String message = "";//返回描述
              String code = "";//返回状态码

               if(returnVal != null && returnVal instanceof String){
                Map<String,Object> map = JSON.parseObject((String) returnVal); //根据返回值类型进行转换
                code = map.get("code")toString();
                message = map.get("message").toString();
                userId = request.getSession().getUserId();//从session获取当前用户信息
                userName = request.getSession().getUserName();
              }


                    //记录此次操作信息
            System.out.print(userName +":"+userId +"请求了"+desc+",{message="+message+"code="+code+"}");
break; } } } } /** * @Description: 获取request */ public HttpServletRequest getHttpServletRequest(){ RequestAttributes ra = RequestContextHolder.getRequestAttributes(); ServletRequestAttributes sra = (ServletRequestAttributes)ra; HttpServletRequest request = sra.getRequest(); return request; } /** * @param joinPoint * @return 环绕通知 * @throws Throwable */ public Object around(ProceedingJoinPoint joinPoint) throws Throwable { return null; } /** * @param joinPoint * @Description 异常通知 */ public void throwing(JoinPoint joinPoint) { System.out.println("异常通知"); } }

3.配置切面

  <aop:aspectj-autoproxy proxy-target-class="true" /> //声明自动为spring容器中那些配置@aspectJ切面的bean创建代理,织入切面
    <bean id="logAspect" class="com.guodu.util.LogAspect"></bean>//直接手动配置添加  
    <aop:config>
          <aop:aspect id="LogAspect" ref="logAspect">
              <aop:pointcut id="log" expression="execution(* com.guodu.controller..*.*(..))"/> //这里只是对Controller 
              <aop:before pointcut-ref="log" method="before"/> //环绕方法
              <aop:after-throwing pointcut-ref="log" method="throwing" throwing="e"/>//异常方法
              <aop:after-returning method="after" pointcut-ref="log" returning="returnVal"/>//后置方法
          </aop:aspect>
    </aop:config>

 4.controller使用注解 

   @RequestMapping(value = {"addUser.action"}, produces = { "application/json;charset=UTF-8" },method=RequestMethod.POST)
    @Log(desc="添加用户")
    @ResponseBody
    public Object addUser(HttpServletRequest request,@RequestParam User user) {
        Map<String , Object> res = new HashMap<String , Object>();
        res.put("code", "0");
        res.put("message", "添加用户成功");try {this.userInfoServiceImpl.add(userInfo);
        } catch (Exception e) {
            res.put("code", "-1");
            res.put("message", "添加用户失败");
            log.error(e.getMessage());
        }    
        return JSON.toJSONString(res);//因为是ajax请求所以返回了json字符串    
    }

 

posted @ 2020-05-29 10:19  请叫我靓仔  阅读(381)  评论(0编辑  收藏  举报