Spring基于注解的AOP开发

基于注解的aop开发步骤:
1. 创建目标接口和目标类(内部有切点)
2. 创建切面类(内部有增强方法)
3. 将目标类和切面类的对象创建权交给 spring
4. 在切面类中使用注解配置织入关系
5. 在配置文件中开启组件扫描和 AOP 的自动代理
6. 测试

接口

package com.code_g.anno;

public interface TargetInterface {
    public void save();
}

目标类

package com.code_g.anno;

import org.springframework.stereotype.Component;

@Component("target")
public class Target implements TargetInterface {

    @Override
    public void save() {
        System.out.println("save data...");
    }
}

切面类

package com.code_g.anno;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Component("myAspect")
@Aspect
public class MyAspect {

    @Before("MyAspect.myPoint()")
//    @Before("myPoint()")
    public void before(){
        System.out.println("前置增强");
    }

    public void after_returning(){
        System.out.println("后置方法");
    }


    @Around("execution(* com.code_g.anno.*.*(..))")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        System.out.println("环绕的前置增强。。。");
        Object proceed = point.proceed();
        System.out.println("环绕的后置增强。。。");
        return proceed;
    }

    public void exception(){
        System.out.println("异常抛出增强...");
    }

    public void after(){
        System.out.println("最终增强...");
    }

    @Pointcut("execution(* com.code_g.anno.*.*(..))")
    public void myPoint(){}
}

配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       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.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
">

<!--    组件扫描-->
    <context:component-scan base-package="com.code_g.anno"/>

<!--    aop自动代理-->
    <aop:aspectj-autoproxy/>
</beans>

测试类

package com.code_g.test;


import com.code_g.anno.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-anno.xml")
public class AopTest {

    @Autowired
    private TargetInterface target;

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


posted @ 2021-05-21 22:00  code-G  阅读(77)  评论(0编辑  收藏  举报