使用注解配置
- 配置IOC容器扫描包
- 配置AspectJ
<aop:aspectj-autoproxy />
- 编写类和切面方法
- 类名上添加注解
@Compoent
和@Aspect
- 方法名上添加注解
- 一共有五种注解:
@Before
:前置通知,方法执行前
@After
:后置通知,方法执行后,即使方法抛出异常也会执行,但是还不能访问方法返回的结果。
@AfterReturning
:返回通知,在方法返回结果之后执行,抛异常则不执行
@AfterThrowing
:异常通知,抛出异常后。可通过throwing属性来指定异常的名字。
@Around
:环绕通知。修饰的方法必须携带ProceedingJoinPoint参数,并且要有返回值。通过调用ProceedingJoinPoint的proceed()方法就来决定目标方法的执行。
ex:@Before("execution(public int per.yrj.Calculator.add(int, int))")
括号里面是指定目标方法。 - JoinPoint参数:当需要获取目标方法的一些信息时可在方法中添加一个形参(如果不需要可以不加)。
- Exception参数:当需要获取目标方法的一些信息时可在方法中添加一个形参(如果不需要可以不加,只能使用在异常通知的方法上)。
- 一共有五种注解:
- 类名上添加注解
在切面方法的注解中添加切面表达式来指定方法的作用范围
ex:"execution(public int per.yrj.Calculator.*(..))"
格式为: 修饰符+返回值+类的全路径.方法名(参数列表)使用@order修饰类指定切面优先级,值越小,优先级越高。
使用@Pointcut来重用切面表达式:- 定义一个空方法,并用@Pointcut来修饰。
- 以后其他需要用到切面表达式的都可以通过该空方法来代替。
ex:
@Product("execution(public int per.yrj.Calculator.*(..))") public void declareJoinPointExpression(){} @Before("declareJoinPointExpression()") public void beforeMethod(){ ... }
使用xml配置
1.配置IOC容器扫描包
2.编写一个类
@Component
public class CalculatorAspect {
// 方法名可随意指定
public void beforeMethod(){
System.out.println("before...");
}
public void afterMethod(){
System.out.println("after...");
}
}
3.配置AspectJ
<!-- 切面类 -->
<bean id="calculatorAspect2" class="per.yrj.xml.CalculatorAspect"/>
<aop:config>
<!--配置切点表达式-->
<aop:pointcut id="pointcut" expression="execution(* per.yrj.xml.impl.CalculatorImpl.*(..))"/>
<!-- 配置切面类 -->
<aop:aspect ref="calculatorAspect2">
<!--配置类中的方法,引用切点表达式-->
<aop:before method="beforeMethod" pointcut-ref="pointcut"/>
<aop:after method="afterMethod" pointcut-ref="pointcut"/>
</aop:aspect>
</aop:config>