//配置类
@Configuration
@EnableAspectJAutoProxy
public class MainConfigOfAOP {
@Bean
public MathCalculator mathCalculator(){
return new MathCalculator();
}
@Bean
public LogAspects logAspects(){
return new LogAspects();
}
}
//业务逻辑组件
public class MathCalculator {
//目标方法
public int div(int i ,int j){
System.out.println("MathCalculator....div....");
return i/j;
}
}
//日志切面组件,在目标方法div()的执行前后等打印相关日志。
@Aspect
public class LogAspects {
@Pointcut("execution(public * com.atguigu.aop.MathCalculator.*(..))")
public void pointCut(){}
@Before("pointCut()")
public void logStart(JoinPoint joinPoint){
Object[] args = joinPoint.getArgs();
System.out.println(""+joinPoint.getSignature().getName()+"运行。。。@Before参数列表是:{"+ Arrays.asList(args)+"}");
}
//JoinPoint作为方法的参数,一定要放在参数的第一位,否则会报错
@After("pointCut()")
public void logEnd(JoinPoint joinPoint){
System.out.println(""+joinPoint.getSignature().getName()+"除法结束@After...");
}
@AfterReturning(value = "pointCut()",returning = "result")
public void logReturn(JoinPoint joinPoint,Object result){
System.out.println(""+joinPoint.getSignature().getName()+"正常返回。。。。@AfterReturning运行结果:{"+result+"}");
}
@AfterThrowing(value = "pointCut()",throwing = "exception")
public void logSException(JoinPoint joinPoint,Exception exception){
System.out.println(""+joinPoint.getSignature().getName()+"异常。。。@AfterThrowing异常信息:{"+exception +"}");
}
//环绕通知,动态代理,手动推进目标方法运行(joinPoint。procced)
// public void log(){
// System.out.println("除法运行。。。参数列表是:{}");
// }
}
//测试类
public class IOCTest_AOP {
@Test
public void test01(){
AnnotationConfigApplicationContext ac=new AnnotationConfigApplicationContext(MainConfigOfAOP.class);
//注意:这里不可以使用注释里面的方式调用目标方法,因为只有由spring容器创建的bean,才能使spring的
//功能。
//MathCalculator mathCalculator=new MathCalculator ();
//mathCalculator.div(1,1);
MathCalculator mathCalculator = ac.getBean(MathCalculator.class);
mathCalculator.div(1,1);
ac.close();
}
}
spring版本:(version:5.2.5);