Spring AOP 之 实现切点、切面

准备jar包

这里写图片描述

定义目标类

1.  目标类接口
public interface ITarger {
    public void HelloWorld();
}
2.  目标类的实现
public class TargetImpl implements ITarger{
    public void HelloWorld(){
        System.out.println("hello world");
    }
}
3. 定义切面支持类

切面支持类提供了通知的实现

public class HelloWorldAspect {
    //前置通知
    public void before(){
        System.out.println("this is before");
    }

    //后置通知
    public void after(){
        System.out.println("this is after");
    }

}

在 XML 中配置切面

<?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 -->
    <bean id="HelloWorld" class="com.target.TargetImpl"></bean>

    <!-- 配置切面 -->
    <bean id="HelloWorldAspect" class="com.aspect.HelloWorldAspect"></bean>
    <aop:config proxy-target-class="true">
        <aop:pointcut expression="execution(* com.target.TargetImpl.*(..))"
            id="HelloWorldPointcut" />
        <aop:aspect ref="HelloWorldAspect">
            <aop:before pointcut-ref="HelloWorldPointcut" method="before" />
            <aop:after pointcut-ref="HelloWorldPointcut" method="after" />
        </aop:aspect>
    </aop:config>
</beans>  

切面的详细解读

这里写图片描述

以上就是切面的所有详细配置信息。
这里写图片描述

aop:pointcut 声明了切点,execution 指定了切点将指向哪个连接点(关于execution上一篇文章有很详细说明,这里不多赘述)
Spring AOP 之 通知、连接点、切点、切面。

这里写图片描述

aop:aspect 中 ref 引入了切面支持类的Bean;aop:before 表示定义前置通知,pointcut-ref 引入切点,method 定义了引用切面辅助类中的哪个方法去执行前置通知。

好啦,就是这么简单啦,如果哪里我没有说清楚,请留言回复我哦。

接下来我们看下执行结果。
这里写图片描述

在 helloworld 执行前首先执行了前置通知,输出了 this is before;
helloworld执行完成后又去执行了后置通知,输出了this is after;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值