aop自定义切面

来源:互联网 发布:中国农大网络远程教育 编辑:程序博客网 时间:2024/05/19 04:07

先定义注解

import java.lang.annotation.*;/** * Created by dubby on 16/3/23. */@Target({ElementType.PARAMETER, ElementType.METHOD})@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface SystemLog {    String description() default "";}

在实现切片

import com.ndkey.web.ResponseData;import com.nington.armstrong.aspect.annotation.SystemLog;import org.apache.logging.log4j.LogManager;import org.apache.logging.log4j.Logger;import org.aspectj.lang.JoinPoint;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.*;import org.springframework.core.annotation.Order;import org.springframework.stereotype.Component;import org.springframework.web.context.request.RequestContextHolder;import javax.servlet.http.HttpSession;import java.lang.reflect.Method;import java.util.Objects;/** * Created by dubby on 16/3/23. */@Aspect@Order(0)@Componentpublic class SystemLogAspect {    private  static  final Logger logger = LogManager.getLogger();    //切点    @Pointcut("@annotation(***.aspect.annotation.SystemLog)")    public  void aspect() {    }    @Around("aspect()")    public Object around(JoinPoint joinPoint){        Object object = null;        try{            object = ((ProceedingJoinPoint)joinPoint).proceed();        } catch (Throwable t){            logger.error(getMethodDescription(joinPoint) + "    "+t.getMessage());            return ResponseData.errorData("server error");        }        return object;    }    /**     * 获取注解中对方法的描述信息     *     * @param joinPoint 切点     * @return 方法描述     * @throws Exception     */    public  static String getMethodDescription(JoinPoint joinPoint) {        String description = "";        try {            String targetName = joinPoint.getTarget().getClass().getName();            String methodName = joinPoint.getSignature().getName();            Object[] arguments = joinPoint.getArgs();            Class targetClass = Class.forName(targetName);            Method[] methods = targetClass.getMethods();            description = "";            for (Method method : methods) {                if (method.getName().equals(methodName)) {                    Class[] clazzs = method.getParameterTypes();                    if (clazzs.length == arguments.length) {                        description = method.getAnnotation(SystemLog. class).description();                        break;                    }                }            }        } catch (ClassNotFoundException e) {            e.printStackTrace();        }        return description;    }}

使用切面

@RequestMapping("/hello")    @SystemLog(description = "hello")    @Transactional    public ResponseData hello() {        Role role = new Role();        role.setId(UUID.randomUUID().toString());        role.setName("测试");        roleMapper.insertSelective(role);        role = new Role();        roleMapper.insert(role);        return ResponseData.successData(role.getName());    }
0 0