CGLIB动态代理在Spring AOP应用中的运用

49 篇文章 1 订阅
4 篇文章 0 订阅

首先子这里我同个一个实例引入CGLIB在spring AOP中的使用

业务启动测试类

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import com.wangyong.learn.project.spring.test.BaseTest;

/**
 * @author Administrator
 */
public class TesAopt extends BaseTest {

    @Autowired
    private TestServiceImpl testService;

    @Test
    public void testAop(){
        testService.aoped();

    }
}

启动测试容器基类,启动spring测试容器

import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.wangyong.learn.project.springboot.start.AopServiceStart;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = AopServiceStart.class)
public class BaseTest {
}

spring应用中需要处理的业务方

public interface TestService {

    void aoped();
}
import org.springframework.stereotype.Component;

@Component
public class TestServiceImpl implements TestService{

    @Override
    public void aoped(){
        System.out.println("处理业务");
    }
}

spring 中AOP切入配置

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

@Component
@Aspect
public class AopConfig {

    @Pointcut("execution(* com.wangyong.learn.project.spring.service..*(..))")
    public void mypoint(){
        System.out.println("切面处理业务");
    }

    @Before("mypoint()")
    public void doAround() throws Throwable {
        System.out.println("before logic");
    }
}

启动Test类

我通过堆栈信息看到 testService 声明的变量其引用指向的对象其实进行过CGLIB生成的一个基础TestServiceImpl的的子类对象

子类对象实质生成的内容,可以通过https://blog.csdn.net/qq_31854907/article/details/108625435 这个例子看看CGLIB技术生成的内容

注意:当被代理的类是一个被final修饰的class 会报一个异常

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testServiceImpl' defined in file [E:\learnCode\learnProject\learnProject\target\classes\com\wangyong\learn\project\spring\service\TestServiceImpl.class]: Initialization of bean failed; nested exception is org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class com.wangyong.learn.project.spring.service.TestServiceImpl: Common causes of this problem include using a final class or a non-visible class; nested exception is java.lang.IllegalArgumentException: Cannot subclass final class com.wangyong.learn.project.spring.service.TestServiceImpl

因此可以理解为在spring容器在初始化完一个bean后,会通过修饰器对已加载的bean进行封装修饰,从实现spring 容器中的另一项核心技术也就是AOP理论

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值