Spring AOP(xml)配置方式

1.导入Aop坐标

2.创建目标接口和目标类


3.创建切面类

package aop;
public class MyAspect {
    public void before() {
        System.out.println("前置增强...");
    }
    public void afterRun() {
        System.out.println("后置增强...");
    }
}

4.将目标对象和切面类的对象创建权交给spring

   <!--目标对象-->
    <bean id="target" class="aop.Target"></bean>
    <!--  切面对象  -->
    <bean id="myAspect" class="aop.MyAspect"></bean>

5.在applicationContext.xml中配置织入关系

配置织入先要创建aop的命名空间,织入就是切点+增强。
所以需要声明一下切面,切面呢已经在上面配置过了,直接引用id。
然后是要进行哪些增强,我们这里写前置增强和后置增强,被增强的对象就是切点就是pointcut。method属性就是指定那个方法是什么增强。execution属性就是指定被增强的方法,属性里面写的是方法签名,
返回类型,返回值,方法全限定名。

  <!--  配置织入: 高速spring框架, 那些方法(切点)需要那些增强 => 需要引入aop的命名空间  -->
    <aop:config>
        <!--  声明切面  -->
        <aop:aspect ref="myAspect">
            <aop:before method="before" pointcut="execution(public void aop.Target.save())"></aop:before>
            <aop:after-returnin method="afterRun" pointcut="execution(public void aop.Target.save())"></aop:after-returnin>
        </aop:aspect>
    </aop:config>

6.测试代码

因为是spring测试所以我们需要导入坐标。

注意此处不可用实现类Target接受注入,一定要用接口接受注入,因为Spring默认是JDK动态代理,需要接口作为参数。具体可去搜索“Spring 接口接受注入”

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class AopTest {
    @Autowired
    private TargetInterface target;

    @Test
    public void test1() {
        target.save();
    }
}




配置环绕增强必须要有一个参数,这个参数就是ProceedingJoinPoint。
要用它去执行切点方法也就是被增强的方法。

下面看一下异常抛出通知
异常抛出通知就是被增强的方法出现异常时执行



当多个增强的切点表达式相同时,我们可以抽取出来相同的切片表达式

posted @ 2022-04-16 15:29  长情c  阅读(599)  评论(0)    收藏  举报