1、AOP基本搭建:
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.8.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>4.3.8.RELEASE</version> </dependency>
@Configuration @ComponentScan(value = "com.aop.test") @EnableAspectJAutoProxy public class ConfigAOP { }
@Aspect @Component public class LogAspects { @Pointcut("execution( public int com.aop.test.MathCaculator.div(..))") public void pointcut(){ } @Before("pointcut()") public void logstart(JoinPoint joinPoint){ System.out.println("@Before aop方法运行开始。。。。获取方法名:"+joinPoint.getSignature().getName()+ "获取方法的参数列表:" +Arrays.asList(joinPoint.getArgs())); } @After("pointcut()") public void logEnd(){ System.out.println("@After: aop方法运算结束"); } @AfterReturning("pointcut()") public void logReturn(){ System.out.println("@AfterReturning: aop方法返回"); } @AfterThrowing(value = "pointcut()",throwing = "exception") public void logException(Exception exception){ System.out.println("@AfterThrowing 打印aop方法异常信息:"); } }
@Component public class MathCaculator { public int div(int a,int b) throws Exception { System.out.println("除法的方法主体"); return a/b; } }
public class Main { public static void main(String[] args) throws Exception { AnnotationConfigApplicationContext annotationConfigApplicationContext=new AnnotationConfigApplicationContext(ConfigAOP.class); System.out.println("容器初始化成功"); MathCaculator MathCaculator = annotationConfigApplicationContext.getBean(MathCaculator.class); MathCaculator.div(1,0); annotationConfigApplicationContext.close(); } }