aop使用总流程
- 导入aop依赖 spring-aspects
- 编写业务类
- 编写切面类
- 将切面类和业务类都加入spring容器(告诉spring哪个是切面类)
- 开启aop功能
1、导入依赖
这里只说明了spring的依赖和aop依赖,其他相关依赖自行导入
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.12.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>4.3.14.RELEASE</version>
</dependency>
2、编写业务类
定义一个除法的方法
public class MathCalculator {
public int div(int i ,int j){
System.out.println("div真正被执行了....");
return i/j;
}
}
3、编写切面类
这一部分是很重要的配置了,需要声明切入点的位置和每个方法在什么时候执行
- Pointcut注解标注所需要切入的类/方法,通过切入点表达式进行配置
- 在通知方法上加入 @Before、@After等注解,标记方法在什么时候执行
- 类上通过 @Aspect 标注是切面类
@Aspect //告诉spring当前类是切面类
public class LogAspects {
/*
抽取公共的切入点表达式
1、本类引用 直接使用方法 例:pointCut()
2、其他的切面引用 全类名
*/
@Pointcut("execution(public int com.lin.aop.a_o_p.MathCalculator.*(..))")
public void pointCut(){}
//@Before()在目标方法之前切入,切入点表达式(指定在那个方法切入)
@Before(" pointCut()") //本类用法
public void logStart(JoinPoint joinPoint){
//可以在切面类方法处传参JoinPoint(必须放在参数第一位) ,获取方法名和方法参数
String methodName = joinPoint.getSignature().getName();
Object[] args = joinPoint.getArgs();
System.out.println(methodName+"运行之前...参数列表是:{"+ Arrays.asList(args)+"}" );
}
@After("com.lin.aop.a_o_p.LogAspects.pointCut()") //外部类用法
public void logEnd(){
System.out.println("除法结束....");
}
@AfterReturning(pointcut = "pointCut()",returning = "result") //定义参数返回接受
public void logReturn(JoinPoint joinPoint,Object result){
System.out.println(joinPoint.getSignature().getName() +"正常返回...运行结果是:{"+result+"}");
}
@AfterThrowing(value = "pointCut()",throwing = "exception")//定义方法异常
public void logExecption(Exception exception){
System.out.println("除法异常返回...异常信息是:{"+exception+"}");
}
}
4、将类放入spring容器
这里将类加入spring容器的方式是 配置类+@Bean的方式
@Configuration
public class MainConfigOfAop {
@Bean
public MathCalculator mathCalculator(){
return new MathCalculator();
}
@Bean
public LogAspects logAspects(){
return new LogAspects();
}
}
5、开启aop功能
在配置类上加上@EnableAspectJAutoProxy注解
@Configuration
@EnableAspectJAutoProxy //开启aop注解
public class MainConfigOfAop {
@Bean
public MathCalculator mathCalculator(){
return new MathCalculator();
}
@Bean
public LogAspects logAspects(){
return new LogAspects();
}
}
6、测试
public class aopTest1 {
@Test
public void test(){
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MainConfigOfAop.class);
MathCalculator mathCalculator = context.getBean(MathCalculator.class);
mathCalculator.div(1,0);
}
}
正常返回
异常返回
1、将业务类和切面类都加入到容器中;告诉spring哪个是切面类(@Aspects)
2、在切面类的每一个通知方法上标注通知注解,告诉Spring何时何地运行(切入点表达式)
3、开启基于注解的aop模式