首页  

基于Aspect注解的spring aop 实例     所属分类 spring 浏览量 1271
增加依赖

spring-boot-starter-aop


切面注解 @Aspect

@Aspect
@Component
public class AspectjHello {

    @Pointcut("execution(* aop.Pet*.sayHello(..))")
    private void log() {
        
    }

    @Before("log()")
    public void doBefore(JoinPoint joinPoint) { 	
    	System.out.println("doBefore run,joinPoint="+joinPoint);       
    }

    @AfterReturning(pointcut = "log()", returning = "object")
    public void doAfterReturning(Object object) {
    	System.out.println("doAfterReturning run,object="+object);
    }
}


@EnableAspectJAutoProxy(proxyTargetClass=true)
proxyTargetClass=true  ,强制使用 cglib代理
proxyTargetClass=false , 基于接口的使用jdk代码, 否则使用 cglib代理

需要开启 AspectJ 自动代理


Pet接口
String sayHello(String name);

public class PetCat implements Pet

//   不实现接口
public class PetTiger{ ... }

测试 jdk 和 cglib 代理


cglib代理类名  
class aop.PetTiger$$EnhancerBySpringCGLIB$$1528e46f

jdk代理类名
class com.sun.proxy.$Proxy19

建议使用  proxyTargetClass=true  ,强制使用 cglib 代理

PetCat cat = (PetCat)ctx.getBean("cat");
proxyTargetClass 设置为true 时 正常 , 设置为 false ,报异常

java.lang.ClassCastException: com.sun.proxy.$Proxy19 cannot be cast to aop.PetCat


aspectjweaver-1.8.13.jar
aspectjrt-1.8.13.jar
只需要aspectjweaver.jar, aspectjrt.jar是aspectjweaver.jar的子集



AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();

		ctx.register(Config.class);
		ctx.refresh();
				
		Pet cat = (Pet)ctx.getBean("cat");
		// proxyTargetClass=false 使用jdk代理   类型转换失败 
		// java.lang.ClassCastException: com.sun.proxy.$Proxy19 cannot be cast to aop.PetCat
		// PetCat cat = (PetCat)ctx.getBean("cat");
		System.out.println(cat.getClass());

		String str = cat.sayHello("java");
		System.out.println(str);

		System.out.println();

		PetTiger tiger = (PetTiger)ctx.getBean("tiger");
		System.out.println(tiger.getClass());
		str = tiger.sayHello("java");
		System.out.println(str);

		ctx.close();


 完整代码
 https://gitee.com/dyyx/hellocode/tree/master/demo/springbootdemo/src/main/java/aop

上一篇     下一篇
spring5配置属性读取机制

spring5模块介绍

spring aop 与 aspectj的区别和联系

AOP知识点

spring aop 内部方法调用拦截说明

spring aop cglib 代理类源码查看