这个Demo是个Demo,基于main启动
启动配置类
@Configuration
@ComponentScan("yuanma.xxx")
//@Import(ImportTest.class)
@EnableAspectJAutoProxy //开启AOP
public class BeanConfig {
}
启动测试类
public class AOPTestApp {
public static void main(String[] args) {
//xml();
ann();
}
/**
* 基于注解的入口
*/
public static void ann() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(BeanConfig.class);
JiSuanQi jiSuanQiImpl = (JiSuanQi) context.getBean("jiSuanQiImpl");
jiSuanQiImpl.jia(2,2);
}
}
被加强的类
/**
* 计算器
*/
public interface JiSuanQi {
int jia(int a, int b);
int jian(int a, int b);
int cheng(int a, int b);
int chu(int a, int b);
}
/**
* 计算器
*/
@Component
public class JiSuanQiImpl implements JiSuanQi {
@Override
public int jia(int a, int b) {
System.out.println("执行了a+b");
return a + b;
}
@Override
public int jian(int a, int b) {
System.out.println("执行了a-b");
return a-b;
}
@Override
public int cheng(int a, int b) {
System.out.println("执行了a*b");
return a*b;
}
@Override
public int chu(int a, int b) {
System.out.println("执行了a/b");
return a/b;
}
}
切面类
切面类就是定义增强代码的
/**
* 增强计算器的切面
*/
@Component
@Aspect
public class JisuanqiAspect {
@Pointcut("execution(* yuanma.leiqiang.aop..*(..))")
public void pointCut() {}
@Before(value = "pointCut()")
public void before(JoinPoint joinPoint) throws Exception{
String name = joinPoint.getSignature().getName();
System.out.println("Before增强了方法"+ name);
}
@After(value = "pointCut()")
public void after(JoinPoint joinPoint) throws Exception{
String name = joinPoint.getSignature().getName();
System.out.println("After增强了方法"+ name);
}
@AfterReturning(value = "pointCut()", returning = "result")
public void afterReturning(JoinPoint joinPoint, Object result) throws Exception{
String name = joinPoint.getSignature().getName();
System.out.println("After增强了方法"+ name + "结果为"+result);
}
@AfterThrowing(value = "pointCut()")
public void afterThrowing(JoinPoint joinPoint) throws Exception{
String name = joinPoint.getSignature().getName();
System.out.println("方法出现了异常"+ name);
}
@Around(value = "pointCut()")
public Object around(ProceedingJoinPoint pjp) throws Throwable{
String name = pjp.getSignature().getName();
System.out.println("环绕通知=>方法执行前"+ name);
Object object = pjp.proceed(pjp.getArgs());//执行我们的方法
System.out.println("环绕通知=>方法执行后"+ name);
return object;
}
}
启动后的打印结果
环绕通知=>方法执行前jia // 环绕通知前 方法执行了
Before增强了方法jia //前置通知执行了
执行了a+b //原方法执行了
环绕通知=>方法执行后jia //环绕通知后 方法执行了
无返回值After增强了方法jia //后置通知 不带返回值的方法执行
带返回值After增强了方法jia结果为4 //后置通知 带返回值的方法执行
|