如何使用注解的方式进行AOP功能实现
1、AOP指的是在程序运行期间动态的将某段代码切入到指定方法指定位置进行运行的编程方式。
package com.gwolf.config;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MainConfigOfAOP {
}

2、要在项目中提供Spring AOP功能,需要导入相关的依赖包。
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>4.3.12.RELEASE</version>
</dependency>

3、有一个业务,我们需要使用AOP在这个业务的执行前后记录一些日志:
package com.gwolf.aop;
public class MathCalculator {
public int div(int i ,int j) {
return i/j;
}
}

4、定义一个日志切面类,切面类里面的方法需要动态感知业务方法运行到哪个步骤。
这个是通过通知方法控制:有前置通知,后置通知,返回通知,异常通知,环绕通知。
package com.gwolf.aop;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
public class LogAspects {
//切入点表达式
@Pointcut("execution(public int com.gwolf.aop.MathCalculator.*(..))")
public void pointCut() {
}
@Before("com.gwolf.aop.LogAspects.pointCut()")
public void logStart() {
System.out.println("除法运行。。参数列表是:{}");
}
@After("com.gwolf.aop.LogAspects.pointCut()")
public void logEnd() {
System.out.println("除法结束运行。。参数列表是:{}");
}
@AfterReturning("com.gwolf.aop.LogAspects.pointCut()")
public void logReturn() {
System.out.println("除法正常返回。。运行结果是:{}");
}
public void logException() {
System.out.println("除法异常。。异常是:{}");
}
}

5、将切面类和业务逻辑类都加入到容器中。
package com.gwolf.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.gwolf.aop.LogAspects;
import com.gwolf.aop.MathCalculator;
@Configuration
public class MainConfigOfAOP {
@Bean
public MathCalculator calculator() {
return new MathCalculator();
}
@Bean
public LogAspects logAspects() {
return new LogAspects();
}
}

6、使用@Aspect注解告诉Spring哪个类是切面类:

7、给配置类中加上@EnableAspectJAutoProxy注解开启基于注解的AOP模式。

8、在junit测试类中执行业务方法。
