Spring AOP 简单的测试 (一)

1,394 阅读1分钟

前言

AOP 和 IOC 是 Spring 的两大门神级别的利器,IOC 前面花了些时间研究了构成,现在尝试解析一下 AOP 的原理,为后面 事务 的学习打一下基础。

STEP 1

在 SpringBoot 中引入 aop 的依赖包

    <dependency>
<!--      使用aop-->
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>

STEP 2

编写一个AOP切入类,比较简单,只会对 bean 的 test() 方法进行增强。

@Aspect
@Component
public class TestAop {

    /**
     * 定义切入点
     */
    @Pointcut("execution(* *.test(..))")
    public void pointCut(){}

    @Before("pointCut()")
    public void beforeTest() {
        System.out.println("beforeTest");
    }

    @After("pointCut()")
    public void afterTest() {
        System.out.println("afterTest");
    }

    @Around("pointCut()")
    public Object arountTest(ProceedingJoinPoint proceedingJoinPoint) {
        System.out.println("before1");
        Object o = null;
        try {
            o = proceedingJoinPoint.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        System.out.println("after1");
        return o;
    }
}

STEP 3

编写一个普通bean,并写上 test() 方法

@Component
public class TestBean {

    private String testStr = "testStr";

    public String getTestStr() {
        return testStr;
    }

    public void setTestStr(String testStr) {
        this.testStr = testStr;
    }

    public void test() {
        System.out.println("test");
    }
}

STEP 4

启动SpringBoot,测试。test() 方法被包裹了其他的代码,我们称之为增强。(对test()进行了增强)

    public static void main(String[] args) {

        ConfigurableApplicationContext context = SpringApplication.run(DemoApplication.class);
        TestBean testBean = (TestBean)
                context.getBean("testBean");
        testBean.test();
    }
控制台输出     
before1
beforeTest
test
after1
afterTest

本次的增强方式,从代码上看,是用了CGLIB实现子类进行增强了。期待后面观察它的生成过程。

全文完。