Spring基于注解的AOP开发(学习笔记)

1. 快速入门

(1)创建目标接口和目标类(内部有切点)

package com.wange.aop;
import org.springframework.stereotype.Component;

public class Target implements TargetInterface {
    public void method() {
        System.out.println("Target方法正在执行");
    }
}

(2)创建切面类(内部有增强方法)

package com.wange.aop;
public class MyAspect {
    //前置增强方法
    public void before(){
        System.out.println("前置代码增强.....");
    }
}

(3)将目标类和切面类的对象创建权交给 spring,在切面类中使用注解配置织入关系

package com.wange.aop;
import org.springframework.stereotype.Component;

@Component("target")
public class Target implements TargetInterface {
    public void method() {
        System.out.println("Target方法正在执行");
    }
}
package com.wange.aop;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

@Component("myAspect")
@Aspect //标注当前MyAspect是一个切面类
public class MyAspect {
    //配置前置通知
    @Before("execution(* com.wange.aop.*.*(..))")
    public void before() {
        System.out.println("前置增强..........");
    }
}

(4)在配置文件中开启组件扫描和 AOP 的自动代理


<context:component-scan base-package="com.wange.aop"/>

<aop:aspectj-autoproxy>aop:aspectj-autoproxy>

(5)测试

import com.wange.aop.TargetInterface;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

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

2. 注解配置 AOP 详解

(1)注解通知的类型

通知的配置语法:@通知注解(“切点表达式")
Spring基于注解的AOP开发(学习笔记)_第1张图片
(2)切点表达式的抽取

同xml配置aop一样,我们可以将切点表达式抽取。抽取方式是在切面内定义方法,在该方法上使用@Pointcut注解定义切点表达式,然后在在增强注解中进行引用。具体如下:**

package com.wange.aop;

import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
@Component("myAspect")
@Aspect //标注当前MyAspect是一个切面类
public class MyAspect {
    //配置前置通知
    @Before("MyAspect.pointcut()")
    public void before() {
        System.out.println("前置增强..........");
    }
    //定义切点表达式
    @Pointcut("execution(* com.wange.aop.*.*(..))")
    public void pointcut(){}
}

你可能感兴趣的:(Spring全家桶,aop,spring,junit)