Spring03

AOP相关概念

名词解释
target(目标对象)
proxy(代理)一个类被aop织入增强后,就会产生一个结果代理类
joinpoint(连接点)指被拦截到的点,在spring中这些点指的是方法
pointcut(切入点)指我们要对哪些joinpoint进行拦截的连接点
advice(通知/增强)指拦截到joinpoint之后要做的事
aspect(切面)切入点和通知的结合
weavinng(织入)指把增强应用到目标对象来创建新的代理对象的过程。spring采用动态代理织入,而aspectj采用编译期织入和类装载期织入
XML快速实现

1.导入aop相关坐标
2.创建目标接口和目标类
3.创建切面类
4.将目标类和切面对象创建权交给spring
5.在applicationcontext.xml中配置织入对象
相关代码

<!--配置目标类-->
<bean id="target" class="com.xxx.aop.Target"></bean>
<!--配置切面类-->
<bean id="myAspect" class="com.xxx.aop.MyAspect"></bean>

<aop:config>
    <!--引用myAspect的Bean为切面对象-->
    <aop:aspect ref="myAspect">
        <!--配置Target的method方法执行时要进行myAspect的before方法前置增强-->
        <aop:before method="before" pointcut="execution(public void com.xxx.aop.Target.method())"></aop:before>
    </aop:aspect>
</aop:config>
表达式详解
execution([修饰符] 返回值类型 包名.类名.方法名(参数))
            *       可省略    *..*.*(..)    //..表示任意个数 包名和类名之间一个点代表当前包下的类,两个点表示当前包及子包下的类
<aop:通知类型 method=“切面类中方法名” pointcut=“切点表达式"></aop:通知类型>
名称标签注解说明
前置通知aop:before@Before指定方法在切入点之前执行
后置通知aop:after-returning@AfterReturning在切入点方法之后执行
环绕通知aop:around@Around在切入点方法之前和之后都执行
异常抛出通知aop:throwing@AfterThrowing指定增强的方法在出现异常时执行
最终通知aop:after@After无论发生什么最终都会执行
切点表达式的抽取
<aop:config>
    <!--引用myAspect的Bean为切面对象-->
    <aop:aspect ref="myAspect">
        <aop:pointcut id="myPointcut" expression="execution(* com.xxx.aop.*.*(..))"/>
        <aop:before method="before" pointcut-ref="myPointcut"></aop:before>
    </aop:aspect>
</aop:config>
基于注解的AOP开发

和xml注解的配置差不多,唯一要注意的是要开启注解的自动配置

@Component("target")
public class Target implements TargetInterface {
    @Override
    public void method() {
        System.out.println("Target running....");
    }
}

@Component("myAspect")
@Aspect
public class MyAspect {
    @Before("execution(* com.itheima.aop.*.*(..))")
    public void before(){
        System.out.println("前置代码增强.....");
    }
}
<!--组件扫描-->
<context:component-scan base-package="com.xxx.aop"/>

<!--aop的自动代理-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
切点表达式的的抽取
@Component("myAspect")
@Aspect
public class MyAspect {
    @Before("MyAspect.myPoint()")
    public void before(){
        System.out.println("前置代码增强.....");
    }
    @Pointcut("execution(* com.xxx.aop.*.*(..))")
    public void myPoint(){}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值