本文主要是介绍aop自定义切面,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
先定义注解
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")@Transactionalpublic 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());}
这篇关于aop自定义切面的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!