美文网首页
Spring AOP

Spring AOP

作者: 一只浩子 | 来源:发表于2021-04-27 18:11 被阅读0次

AOP(Aspect Orient Programming),我们一般称为面向方面(切面)编程,作为面向对象的一种补充,用于处理系统中分布于各个模块的横切关注点,比如事务管理、日志、缓存等等。AOP实现的关键在于AOP框架自动创建的AOP代理,AOP代理主要分为静态代理和动态代理,静态代理的代表为AspectJ;而动态代理则以Spring AOP为代表。

Spring AOP使用的动态代理,所谓的动态代理就是说AOP框架不会去修改字节码,而是在内存中临时为方法生成一个AOP对象,这个AOP对象包含了目标对象的全部方法,并且在特定的切点做了增强处理,并回调原对象的方法。

Spring AOP中的动态代理主要有两种方式,JDK动态代理和CGLIB动态代理。JDK动态代理通过反射来接收被代理的类,并且要求被代理的类必须实现一个接口。JDK动态代理的核心是InvocationHandler接口和Proxy类。

如果目标类没有实现接口,那么Spring AOP会选择使用CGLIB来动态代理目标类。CGLIB(Code Generation Library),是一个代码生成的类库,可以在运行时动态的生成某个类的子类,注意,CGLIB是通过继承的方式做的动态代理,因此如果某个类被标记为final,那么它是无法使用CGLIB做动态代理的。

定义一个类

@Component
public class Person {
    @Mylog
    public void sayHello() {
        System.out.println("seyHello");
    }
}

定义Aspect

@Aspect
@Component
public class AspectTest {
    // 自定义注解Mylog
    @Pointcut("@annotation(com.zenghao.testweb.common.aop.Mylog)")
    public void pointcut() {
    }

    @Before("pointcut()")
    public void before() {
        System.out.println("~~before~~");
    }
    @After("pointcut()")
    public void after() {
        System.out.println("~~after~~");
    }
}

运行测试

    @Autowired
    private Person person;

    @RequestMapping("/hello")
    public Object hello(){
        person.sayHello();
        return "hello test";
    }

结果

~~before~~
seyHello
~~after~~

Spring AOP的动态代理是在每次运行时动态的增强,生成AOP代理对象。

相关文章

网友评论

      本文标题:Spring AOP

      本文链接:https://www.haomeiwen.com/subject/rtdnqltx.html