创建一个aspect切面类
@Aspect // FOR AOP
@Order(99) // 控制多个Aspect的执行顺序,越小越先执行
@Component
public class TestAspect {
@Autowired
private AopService aopService; //server层,测试aop中可以通过autowire,调用service里面的方法
//execution 方式
@Pointcut("execution(* com.zcy.controller..*.show2(..))")
public void pointCutZ(){
}
//自定义注解方式,当然可以放spring自带的注解,使用方式一样
@Pointcut(value = "@annotation(com.zcy.annotation.WxdAnnotation)")
public void wxdAnnotation() {
}
//使用零 及:&& || 方法的使用
@Before("pointCutZ() && wxdAnnotation()")
public void show2Test(){
System.out.println("-----LogAspect---show2test");
}
//使用一
@Before("wxdAnnotation()")
public void beforeWxdTest(JoinPoint point){
System.out.println("beforeWxdTest:"+point.getSignature().getName());
}
//使用二
@Before("@annotation(com.zcy.annotation.ZcyAnnotation)")
public void beforeZcyTest(JoinPoint point){
System.out.println("beforeZcyTest:"+point.getSignature().getName());
}
//使用三
@Before("@annotation(study)")
public void beforeTest(JoinPoint point, StudyAnnotation study) throws Throwable {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
// 记录下请求内容
System.out.println("URL : " + request.getRequestURL().toString());
System.out.println("HTTP_METHOD : " + request.getMethod());
System.out.println("IP : " + request.getRemoteAddr());
System.out.println("beforeTest:" + study.name());
System.out.println("typename:"+point.getSignature().getDeclaringTypeName());
System.out.println("funName:"+point.getSignature().getName());
Object[] args = point.getArgs();
if(args !=null && args.length>0){
ShowObject showObject = (ShowObject)args[0];
System.out.println(showObject.getId()+","+showObject.getSysCode());
}
}
//后置异常通知 GloableException 自定义的异常。
@AfterThrowing(value = "@annotation(study)",throwing = "ex")
public void throwsTest(JoinPoint jp,GlobalErrException ex,StudyAnnotation study){
//没看到效果
System.out.println("方法异常时执行....."+ex.getiErrorInfo().getMgs());
}
@After("@annotation(study)")
public void afterTest(JoinPoint point, StudyAnnotation study) {
System.out.println("afterTest:" + study.name());
}
@AfterReturning(returning = "ret", value = "@annotation(study)")
public void afterReturnTest(Object ret,StudyAnnotation study){
System.out.println("afterReturnTest:"+JsonUtility.object2String(ret));
aopService.test1();
}
//环绕通知,环绕增强,相当于MethodInterceptor
@Around("@annotation(study)")
public Object arround(ProceedingJoinPoint pjp,StudyAnnotation study) throws Throwable{
System.out.println("arround---start");
Object o = pjp.proceed();
System.out.println("方法环绕proceed,结果是 :" + o);
System.out.println("arround---end");
return o;
}
自定义注解
WxdAnnotation StudyAnnotation ZcyAnnotation
代码一样,贴出一个
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface StudyAnnotation {
String name();
}
controller 层
@Api("aop相关")
@RestController
@RequestMapping("aop")
public class AopController {
@Autowired
private AopService aopService;
@WxdAnnotation(name="show1wxd")
@ZcyAnnotation(name = "show1zcy")
@StudyAnnotation(name="show")
@ApiOperation("show")
@RequestMapping(value = "show",method = RequestMethod.GET)
public String show(){
System.out.println("show-----");
return "OK";
}
@WxdAnnotation(name="s")
@ApiOperation("show2")
@RequestMapping(value="/show2",method = RequestMethod.GET)
public String show2() {
System.out.println("show22-----");
return "OK2";
}
@StudyAnnotation(name="show3")
@ApiOperation("show3")
@RequestMapping(value="/show3",method = RequestMethod.POST)
public ShowObject show3(@RequestBody ShowObject showObject) {
System.out.println("show3-----");
ShowObject showObject1 = new ShowObject("2222","bbbbbb");
return showObject1;
}
@ApiOperation("show4")
@RequestMapping(value="/show4",method = RequestMethod.GET)
public ResultBody show4() throws Exception{
System.out.println("show4-----");
ResultBody showObject1 = new ResultBody();
if(1==1){
throw new GlobalErrException(BusinessErrorInfo.ERROR);
}
return showObject1;
}
}
dto中ShowObject对象
@Data
@AllArgsConstructor
public class ShowObject {
private String id;
private String sysCode;
}
结果:调用show 结果
arround---start
beforeTest:show
typename:com.zte.daas.zcy.controller.AopController
funName:show
beforeWxdTest:show
beforeZcyTest:show
show-----
方法环绕proceed,结果是 :OK
arround---end
afterTest:show
afterReturnTest:"OK"
--AopService--test1
show4的结果 注释了aroud方法。异常时:执行到after 后,再执行异常部分
URL : http://localhost:8088/aop/show4
HTTP_METHOD : GET
IP : 0:0:0:0:0:0:0:1
beforeTest:show4
typename:com.zcy.controller.AopController
funName:show4
show4-----
afterTest:show4
方法异常时执行.....失败11111111
2018-04-19 13:58:18.266 [http-nio-8088-exec-1] ERROR c.z.common.exception.GlobalErrExceptionHandle - busiErrorHandlerOverJson:9999:失败11111111
二: 切面方法说明
@Aspect
作用是把当前类标识为一个切面供容器读取
@Before
标识一个前置增强方法,相当于BeforeAdvice的功能
@AfterReturning 正常非异常的情况退出调用,否则不调用
后置增强,相当于AfterReturningAdvice,方法退出时执行
@AfterThrowing 异常调用
异常抛出增强,相当于ThrowsAdvice
@After
final增强,不管是抛出异常或者正常退出都会执行
@Around
环绕增强,相当于MethodInterceptor
3 execution切点函数
execution函数用于匹配方法执行的连接点,语法为:
execution(方法修饰符(可选) 返回类型 方法名 参数 异常模式(可选))
参数部分允许使用通配符:
* 匹配任意字符,但只能匹配一个元素
.. 匹配任意字符,可以匹配任意多个元素,表示类时,必须和*联合使用
+ 必须跟在类名后面,如Horseman+,表示类本身和继承或扩展指定类的所有类
示例中的* chop(..)解读为:
方法修饰符 无
返回类型 *匹配任意数量字符,表示返回类型不限
方法名 chop表示匹配名称为chop的方法
参数 (..)表示匹配任意数量和类型的输入参数
异常模式 不限
4 更多切点函数
除了execution(),Spring中还支持其他多个函数,这里列出名称和简单介绍,以方便根据需要进行更详细的查询
4.1 @annotation()
表示标注了指定注解的目标类方法
例如 @annotation(org.springframework.transaction.annotation.Transactional) 表示标注了@Transactional的方法
4.2 args()
通过目标类方法的参数类型指定切点
例如 args(String) 表示有且仅有一个String型参数的方法
4.3 @args()
通过目标类参数的对象类型是否标注了指定注解指定切点
如 @args(org.springframework.stereotype.Service) 表示有且仅有一个标注了@Service的类参数的方法
4.4 within()
通过类名指定切点
如 with(examples.chap03.Horseman) 表示Horseman的所有方法
4.5 target()
通过类名指定,同时包含所有子类
如 target(examples.chap03.Horseman) 且Elephantman extends Horseman,则两个类的所有方法都匹配
4.6 @within()
匹配标注了指定注解的类及其所有子类
如 @within(org.springframework.stereotype.Service) 给Horseman加上@Service标注,则Horseman和Elephantman 的所有方法都匹配
4.7 @target()
所有标注了指定注解的类
如 @target(org.springframework.stereotype.Service) 表示所有标注了@Service的类的所有方法
4.8 this()
大部分时候和target()相同,区别是this是在运行时生成代理类后,才判断代理类与指定的对象类型是否匹配
5 逻辑运算符
表达式可由多个切点函数通过逻辑运算组成
5.1 &&
与操作,求交集,也可以写成and
例如 execution(* chop(..)) && target(Horseman) 表示Horseman及其子类的chop方法
5.2 ||
或操作,求并集,也可以写成or
例如 execution(* chop(..)) || args(String) 表示名称为chop的方法或者有一个String型参数的方法
5.3 !
非操作,求反集,也可以写成not
例如 execution(* chop(..)) and !args(String) 表示名称为chop的方法但是不能是只有一个String型参数的方法