Spring纯注解方式使用AOP

时间:2022-12-05 16:56:27

Aop配置类

package com.mt.spring5.aopanno;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@Configuration//配置类
@ComponentScan(basePackages = {"com.mt.spring5.aopanno"})//开启组件扫描
@EnableAspectJAutoProxy(proxyTargetClass = true) //开启自动生成代理类
public class AopConfig {
}

需要Aop代理增强的类

package com.mt.spring5.aopanno;

import org.springframework.stereotype.Component;

@Component
public class User {
public void add(){
System.out.println("add......");
}
}

代理类

package com.mt.spring5.aopanno;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.junit.jupiter.api.Order;
import org.springframework.stereotype.Component;

@Component
@Aspect
@Order(2)
public class UserProxy {
@Pointcut(value="execution(* com.mt.spring5.aopanno.User.add(..))")//定义切入点
public void pointcut(){}
@Before(value="pointcut()")//使用定义的切入点
public void before(){
System.out.println("befor");
}

//最终通知,无论有没有执行都通知
@After(value="execution(* com.mt.spring5.aopanno.User.add(..))")//不使用定义的切入点,手动输入切入点
public void after(){
System.out.println("after");
}
//执行之后再在通知
@AfterReturning(value="execution(* com.mt.spring5.aopanno.User.add(..))")
public void afterReturning(){
System.out.println("afterReturning");
}
//又异常菜通知
@AfterThrowing(value="execution(* com.mt.spring5.aopanno.User.add(..))")
public void afterThorowing(){
System.out.println("afterThorowing");
}


@Around(value="execution(* com.mt.spring5.aopanno.User.add(..))")
public void arround(ProceedingJoinPoint pj) throws Throwable {
System.out.println("环绕前");
pj.proceed();
System.out.println("环绕后");
}
}

测试类

package com.mt.spring5;

import com.mt.spring5.aopanno.AopConfig;
import com.mt.spring5.aopanno.User;
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class TestMain {

@Test
public void testAopAutoNoXml(){
ApplicationContext context = new AnnotationConfigApplicationContext(AopConfig.class);
User user = context.getBean("user",User.class);
user.add();
}
}