Spring aop

我与影子孤独终老i 提交于 2020-02-26 22:19:33

aop思想

在一个执行一个方法时如果我们想要在执行方法前后者后增加其他的方法,这时我们就需要去修改原方法的代码十分的麻烦。由此我们引入aop

执行aop的三种方法

使用xml文档
1如果想要在方法前执行创建一个类并且继承MethodBeforeAdvice
如果想要在方法后执行创建一个类并且继承AfterReturningAdvice

2在xml文件中编写对应的bean和aop,

   <aop:config>
        <aop:pointcut id="UserPointCut" expression="execution(* com.xxr.mapper.Impl.UserImpl.*(..))"></aop:pointcut>
        <aop:advisor advice-ref="After" pointcut-ref="UserPointCut"></aop:advisor>
        <aop:advisor advice-ref="Befor" pointcut-ref="UserPointCut"></aop:advisor>
 </aop:config>

第二种方式
编写一个要插入的实体类在xml文件注册即可
编写对应的aop

<aop:config>
   <aop:aspect ref="BATest">
        <aop:pointcut id="BA" expression="execution(* com.xxr.mapper.Impl.UserImpl.*(..))"></aop:pointcut>
     <aop:before method="befor" pointcut-ref="BA"></aop:before>
      <aop:after method="after" pointcut-ref="BA"></aop:after>
</aop:aspect>
</aop:config>

第三种方式注解(推荐使用)
1 在xml中开启aop注解即可

  <aop:aspectj-autoproxy></aop:aspectj-autoproxy>

2 编写实体类并在实体类上添加注解即可

@Aspect()
public class BATest2 {
    @Before("execution(* com.xxr.mapper.Impl.UserImpl.*(..))")
    public void befor(){

        System.out.println("befor");
    }
    @After("execution(* com.xxr.mapper.Impl.UserImpl.*(..))")
    public void after(){
        System.out.println("after");
    }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!