首先子这里我同个一个实例引入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理论