您的位置:首页 > 运维架构

aop自定义切面

2016-03-30 15:15 411 查看

先定义注解

import java.lang.annotation.*;

/**
* Created by dubby on 16/3/23.
*/
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @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)
@Component
public 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());
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: