1.业务类
public class MathCalculator {
public int div(int i, int j) {
System.out.println("MathCalculator---div");
return i / j;
}
}
2.切面类
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import java.util.Arrays;
@Aspect
public class LogAspects {
@Pointcut("execution(public int com.atguigu.gmall.aop.MathCalculator.div(int, int))")
public void pointCut() {
}
@Before("pointCut()")
public void logStart(JoinPoint joinPoint) {
Object[] args = joinPoint.getArgs();
System.out.println("" + joinPoint.getSignature().getName() + "运行。。。参数列表是:{" + Arrays.asList(args) + "}");
}
@After("pointCut()")
public void logEnd(JoinPoint joinPoint) {
System.out.println("" + joinPoint.getSignature().getName() + "结束。。。");
}
@AfterReturning(value = "pointCut()", returning = "result")
public void logReturn(JoinPoint joinPoint, Object result) {
System.out.println("" + joinPoint.getSignature().getName() + "正常返回。。。运行结果:{" + result + "}");
}
//JoinPoint一定要出现在参数列表的第一位
@AfterThrowing(value = "pointCut()", throwing = "exception")
public void logException(JoinPoint joinPoint, Exception exception) {
System.out.println("" + joinPoint.getSignature().getName() + "异常。。。异常信息:{" + exception + "}");
}
}
3.配置类
import com.atguigu.gmall.aop.LogAspects;
import com.atguigu.gmall.aop.MathCalculator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
/**
* 1.定义一个业务逻辑类(MathCalculator)
* 2.定义一个日志切面类(LogAspects):切面类里面的方法需要动态感知MathCalculator.div运行到
* 通知方法:
* 返回通知(@AfterReturning):logReturn:在目标方法div正常返回之后运行
* 异常通知(@AfterThrowing):logException:在目标方法div出现异常之后运行
* 环绕通知(@Around):动态代理,手动推进目标方法运行(joinPoint.procced())
* 3.给切面类的目标方法标注何时何地运行(通知注解)
* 4.将切面类和业务逻辑类(目标方法所在类)都加入到容器中
* 5.告诉spring哪个类是切面类(给切面类加注解:@Aspect)
* 6.给配置类加@EnableAspectJAutoProxy(开启基于注解的aop模式)
*
* @EnableXXX,开启XXX功能
*
* 三步:
* 1)将业务逻辑组件和切面类都加入到容器中;告诉spring哪个是切面类(@Aspect)
* 2)在切面类上的每一个通知方法上标注通知注解,告诉spring何时何地运行(切入点表达式)
* 3)开启基于注解的aop模式;@EnableAspectJAutoProxy
*
*
*/
@EnableAspectJAutoProxy
@Configuration
public class MainConfigOfAOP {
@Bean
public MathCalculator calculator() {
return new MathCalculator();
}
@Bean
public LogAspects logAspects() {
return new LogAspects();
}
}
4.测试类
public class AopTest {
@Test
public void run1() {
ApplicationContext ac = new AnnotationConfigApplicationContext(MainConfigOfAOP.class);
MathCalculator bean = ac.getBean(MathCalculator.class);
// bean.div(2, 1);
bean.div(2, 0);
}
}