Spring学习笔记9-AOP使用

前面大概了解了下AOP的术语和通知类型,本节就介绍下AOP的使用

参考文档:Spring Boot AOP基本原理及实践(附带Demo)_小小_飞侠的博客-CSDN博客

一.前置准备

1.xml中导入aop

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
    http://www.springframework.org/schema/aop 
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">

   <!-- bean definition & AOP specific configuration -->

</beans>

2.依赖导入

  • aspectjrt.jar

  • aspectjweaver.jar

  • aspectj.jar

  • aopalliance.jar

如果是maven管理依赖,直接在pom.xml文件中引入依赖

二.AOP使用

1.spring-api实现

public class Log implements MethodBeforeAdvice {
    /**
     * method 被调用方法对象
     * args 被调用的方法的参数
     * target 被调用方法的目标对象
     * */

    @Override
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println("这是切面");
    }
}

业务代码(此处省略)

配置xml

<bean id="log" class="com.xx.Log.Log" />
    <aop:config>
        <aop:pointcut expression="execution(* com.xx.service.UserServiceImpl.add(..))" id="pointcut" />
        <aop:advisor advice-ref="log" pointcut-ref="pointcut" />
    </aop:config>

说明:

execution()里面参数:第一个是返回值,第二个是路径名称,比如com.xx.service.UserServiceImpl.add()是指业务实现类的具体方法,也就是切入点地方

add(..)代表add参数

log是实现切面的类

对于其他通知类型实现,原理是一样的,只是实现的api和参数会有稍许差别。

2.自定义类实现

public class TestAop  {
    public void before(){
        System.out.println("自定义实现aop");
    }
}

业务代码(此处省略)

配置xml

 <aop:config>
        <aop:aspect>
            <aop:pointcut id="pointcut" expression="execution(* com.xx.service.UserServiceImpl.add(..))/>
            <aop:before method="before" pointcut-ref="pointcut" />
        </aop:aspect>
    </aop:config>

3.注解实现

@Aspect
public class TestAop  {
    @Before("expression=(* LeanSpring.aop.test.Hello1.print()")
    public void before(){
        System.out.println("注解实现aop");
    }


    @After("expression=(* LeanSpring.aop.test.Hello1.print()")
    public void after(){
        System.out.println("注解实现aop");
    }


    @Around("expression=(* LeanSpring.aop.test.Hello1.print()")
    public void around(){
        System.out.println("注解实现aop");
    }
}

业务代码(忽略)

配置xml

#说明:声明自动为spring容器中那些配置@aspectJ切面的bean创建代理,织入切面
<aop:aspectj-autoproxy/>

以上是3种实现aop的方法,具体的业务代码此处并未详细书写,大家可以自行进行尝试,自己学习后,感触AOP就是在某个方法的切面点去实现某个切面类,具体的切面类由作者自己去写逻辑,比如安全,权限等,AOP是学习了两遍才大概明白,书读百遍,其意自现,大家也可以多去查阅其他资料,帮助理解和学习 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值