使用AspectJ注解来实现AOP-----前置通知
1.导入必要jar包
aopalliance.jar
aspectj-1.8.4.jar
aspectjweaver-1.5.0.jar
commons-logging-1.1.3.jar
mysql-connector-java-5.1.7-bin.jar
spring-aop-4.0.0.RELEASE.jar
spring-aspects-4.0.0.RELEASE.jar
spring-beans-4.0.0.RELEASE.jar
spring-context-4.0.0.RELEASE.jar
spring-core-4.0.0.RELEASE.jar
spring-expression-4.0.0.RELEASE.jar
2在配置文件中加入aop命名空间,配置文件如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!-- 配置自动扫描的包 -->
<context:component-scan base-package="com.hcx.spring.aop.impl"></context:component-scan>
<!-- 使AspjectJ注解起作用: 自动为匹配的类生产代理对象 -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
在代理类中写切面方法,并加上对应注解,注解有以下几类:
@Before:前置通知,在方法执行前执行
@After:后置通知,在方法执行后执行
@AfterRunning:返回通知,在方法返回结果之后执行
@AfterThrowing:异常 通知,在方法抛出异常之后通知
@Around:环绕通知,围绕着方法执行
在注解中要标注出目标方法,可以使用*占位符。
该包下的所有类的所有方法
@Before("execution(* com.hcx.spring.aop.impl.*.*(int, int))")
在代理方法中可以使用JoinPoint 参数,获取目标方法的相关信息
代理类:
//把日志类声明为切面:把该类放入到ioc容器中
//再声明为切面
@Aspect
@Component
public class LoggingAspect {
//声明该方法是一个前置通知,在目标方法之前
@Before("execution(* com.hcx.spring.aop.impl.*.*(int, int))")
//JoinPoint:通过该参数可以获得 目标方法相关信息
public void beforeMethod(JoinPoint joinPoint) {
String methodName= joinPoint.getSignature().getName();
List<Object> args=Arrays.asList(joinPoint.getArgs());
System.out.println("The method "+methodName+" begin");
}
}
计算器实现类:
package com.hcx.spring.aop.impl;
import org.springframework.stereotype.Component;
@Component()
public class ArithmeticCalculatorImpl implements ArithmeticCalculator {
@Override
public int add(int i, int j) {
int result= i+j;
return result;
}
@Override
public int sub(int i, int j) {
int result= i-j;
return result;
}
@Override
public int mul(int i, int j) {
int result= i*j;
return result;
}
@Override
public int div(int i, int j) {
int result= i/j;
return result;
}
}