Day03
注解名 | 作用 |
---|---|
@EnableAspectJAutoProxy | 开启基于注解的AOP模式 |
@Pointcut | 定义切点 |
@Aspect | 定义(说明)切面类 |
@Before | 在目标方法运行前运行 |
@After | 在目标方法运行后运行 |
@AfterReturning | 在目标正常返回后运行 |
@AfterThrowing | 在目标出现异常后运行 |
MyConfigAOP
package com.atguigu.config;
import com.atguigu.aop.LogAspects;
import com.atguigu.aop.MathCalculator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@EnableAspectJAutoProxy //
@Configuration
public class MyConfigOfAOP {
//业务逻辑类加入容器中
@Bean
public MathCalculator calculator(){
return new MathCalculator();
}
//切面类加入容器
@Bean
public LogAspects aspects(){
return new LogAspects();
}
}
MathCalculator
package com.atguigu.aop;
public class MathCalculator {
public int div(int i,int j){
System.out.println("MathCalculator....div....");
return i/j;
}
}
LogAspects
package com.atguigu.aop;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import java.util.Arrays;
@Aspect
public class LogAspects {
//抽取公共的切入点表达式
//本类引用
//其他的切面引用 全类名
@Pointcut("execution(public int com.atguigu.aop.MathCalculator.*(..))") //定义切点
public void pointCut(){};
//前置通知
@Before("pointCut()")
public void logStrat(JoinPoint joinPoint){ //JoinPoint一定要在参数的第一位
Object[] args = joinPoint.getArgs();
System.out.println(""+joinPoint.getSignature().getName()+"运行。。。。参数列表是:{"+ Arrays.asList(args)+"}");
}
//后置通知
@After("com.atguigu.aop.LogAspects.pointCut()")
public void logEnd(JoinPoint joinPoint){
System.out.println(""+joinPoint.getSignature().getName()+"结束。。。。");
}
//返回通知
@AfterReturning(value = "pointCut()",returning = "result")
public void logReturn(Object result){
System.out.println("除法正常返回。。。。运行结果是:{"+result+"}");
}
//异常通知
@AfterThrowing(value = "pointCut()",throwing = "exception")
public void logException(JoinPoint joinPoint,Exception exception){
System.out.println(""+joinPoint.getSignature().getName()+"异常。。。。异常信息是:{"+exception+"}");
}
}
Test
package com.atguigu.test;
import com.atguigu.aop.MathCalculator;
import com.atguigu.config.MyConfigOfAOP;
import com.atguigu.config.MyConfigOfAutowired;
import com.atguigu.dao.BookDao;
import com.atguigu.service.BookService;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class IOCAOP {
@Test
public void test01(){
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(MyConfigOfAOP.class);
MathCalculator calculator = context.getBean(MathCalculator.class);
calculator.div(1,1);
context.close();
}
}