Spring入门(Schema-based AOP其二)

基于使用配置的AOP的实现

Schema-based AOP

Spring所有的切面和通知偶必须放在一个<aop:config>内(可以配置多个包含<aop:config>元素),每一个<aop:config>可以包含pointcut,advisor元素(它们必须按照这个顺序进行声明)
<aop:config>风格的配置大量使用了Spring的自动代理机制

然后看一下基于这种配置的AOP的实现
首先声明一个aspect的xml,然后是两个配置<aop:config><aop:aspect>
然后看一下下边这个例子

<aop:config>
    <aop:aspect ref="aBean">
        ...
    </aop:aspect>
</aop:config>

<bean id="aBean" class="...">
    ...
</bean>

声明<aop:config>,里边有<aop:aspect>这个属性配置,它有id和ref,ref会引用另外一个Bean。这句话的意思,就是把引用的这个Bean作为一个切面来声明,这个切面的id就是myAspect。

然后看一下代码,这里边有两个类,一个是MoocAspect,这个类为切面类,还有一个类aspectBiz为我们要实现的业务类。
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.xsd  
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">

    <bean id="moocAspect" class="com.imooc.aop.schema.advice.MoocAspect"></bean>

    <bean id="aspectBiz" class="com.imooc.aop.schema.advice.biz.AspectBiz"></bean>

    <aop:config>
        <aop:aspect id="moocAspectAOP" ref="moocAspect">

        </aop:aspect>
    </aop:config>

 </beans>

属性id为moocAspectAOP,然后设置引用为moocAspect,也就是那个切面类。

配置切入点pointcut

在前边的内容之后,下边要做的就是声明切入点
对应pointcut,有相应的说明
这里写图片描述

举例来说明
这里写图片描述
之前说到Spring AOP或者Spring支持的AspectJ,这部分是都支持的,以下的是只有Spring AOP里边自己支持的
这里写图片描述
这里写图片描述
这里写图片描述
相应的,这些的说明可以查找Spring的官方文档。
不用强记,只要知道有很多的类型,使用时查找文档即可。

然后看一下我们刚才的例子中的pointcut怎么来声明。

<aop:config>
    <aop:pointcut id="businessService" 
            expression="execution(*com.xyz.myapp.service..(..))"/>
</aop:config>

首先由pointcut的id,还有就是expression,里边的内容代表的意义就是执行这个包下面所有类的任何类型方法的时候。

如果要配置一个完整的aop:config,把pointcut加进去会是什么样

<aop:config>
    <aop:aspect ref="aBean">
        <aop:pointcut id="businessService" 
            expression="execution(*com.xyz.myapp.service..(..))"/>
        ...
    </aop:aspect>
</aop:config>

然后在代码中配置一下。

<bean id="moocAspect" class="com.imooc.aop.schema.advice.MoocAspect"></bean>

<bean id="aspectBiz" class="com.imooc.aop.schema.advice.biz.AspectBiz"></bean>

<aop:config>
    <aop:aspect id="moocAspectAOP" ref="moocAspect">
        <aop:pointcut id="moocPiontcut" 
            expression="execution(* com.imooc.aop.schema.advice.biz.*Biz.*(..))"/>
    </aop:aspect>
</aop:config>

这里要匹配AspectBiz类里边所有的方法。
这里*Biz标识以Biz结尾的类,其实就是AspectBiz这个类。

这就是切入点的配置。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值