美文网首页
AOP-使用注解配置AOP

AOP-使用注解配置AOP

作者: Yanl__ | 来源:发表于2019-12-25 09:36 被阅读0次

基于Aspect

  1. 引入xmlns:context
    spring 不会自动去寻找注解,必须告诉spring 哪些包下的类中可能有注解
<context:component-scan base-package="com.bjsxt.advice"></context:component-scan>
  1. 在通知类中配置
    2.1 给类添加@Component 。@Component 类被spring 管理

2.1.1 相当于<bean/>
2.1.2 如果没有参数,把类名首字母变小写,相当于<bean id=””/>
2.1.3 @Component(“自定义名称”)
2.2 @Aspect 相当于<aop:aspect/>表示通知方法在当前类中

@Component
@Aspect
public class MyAdvice {
@Before("com.steer.test.Demo.demo1()")
public void mybefore(){
    System.out.println("前置");
}
@After("com.steer.test.Demo.demo1()")
public void myafter(){
    System.out.println("后置通知");
}
@AfterThrowing("com.steer.test.Demo.demo1()")
public void mythrow(){
    System.out.println("异常通知");
}
@Around("com.steer.test.Demo.demo1()")
public Object myarround(ProceedingJoinPoint p) throws
Throwable{
    System.out.println("环绕-前置");
    Object result = p.proceed();
    System.out.println("环绕-后置");
return result;
}
}

2.3 在方法上添加@Pointcut,定义成切点

@Component
public class Demo {
@Pointcut("execution(* com.steer.test.Demo.demo1())")
public void demo1() throws Exception{
    // int i = 5/0;
    System.out.println("demo1");
}
}

相关文章

网友评论

      本文标题:AOP-使用注解配置AOP

      本文链接:https://www.haomeiwen.com/subject/fpkogctx.html