spring的AspectJ注解
AspectJ的通知类型
- @Before:前置通知,在方法的执行之前执行
- @After:后制通知,在方法的执行之后执行
- @AfterRunning:返回通知,在方法返回结果之后执行
- @AfterThrowing:异常通知,在方法抛出异常之后执行
- @Around:环绕通知,围绕着方法执行
- 加入相应的jar包
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.7.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/aspectj/aspectjrt -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.7.4</version>
</dependency>
- 在配置文件中加入自动扫描、AspjectJ注解生效
<context:component-scan base-package="spring.aop.impl"></context:component-scan>
<!-- 使AspectJ起着作用:自动为匹配的类生成代理对象-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
- 写面向切面的类
//把这个类声明为一个切面:1. 将该类放到IOC容器中;2. 声明为切面
@Aspect
@Component
public class LoggingAspect {
// 声明该方法为前置通知:在目标方法开始之前执行
@Before("execution(public int spring.aop.impl.ArithmeticCalculator.*(int,int))")
public void beforeMethod(JoinPoint joinPoint){
String methodName = joinPoint.getSignature().getName();
List<Object> args = Arrays.asList(joinPoint.getArgs());
System.out.println("The method "+methodName+" begins with "+args);
}
// 后置通知:在目标方法执行后执行(无论是否有异常),但是不能访问目标方法执行的结果
@After("execution(* spring.aop.impl.ArithmeticCalculator.*(*,* ))")
public void afterMethod(JoinPoint joinPoint){
String methodName = joinPoint.getSignature().getName();
List<Object> args = Arrays.asList(joinPoint.getArgs());
System.out.println("The method "+methodName+" ends");
}
}
- 在主函数中调用
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
ArithmeticCalculator arithmeticCalculator = (ArithmeticCalculator) applicationContext.getBean("arithmeticCalculator");
int result = arithmeticCalculator.div(12,4);
System.out.println("result:"+result);
}
- 运行结果