一、AOP:
Spring的问题:

Spring的AOP解决:

示例:

二、Spring AOP
AspectJ:java社区里最完整最流行的AOP框架。
在Spring2.0以上版本中,可以使用基于AspectJ注解或基于XML配置的AOP。

1)、首先加入jar包:
com.springsource.org.aopalliance-1.0.0.jar
com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
spring-aop-4.0.4.RELEASE.jar
spring-aspects-4.0.4.RELEASE.jar
commons-logging-1.1.3.jar
spring-beans-4.0.4.RELEASE.jar
spring-context-4.0.4.RELEASE.jar
spring-core-4.0.4.RELEASE.jar
spring-expression-4.0.4.RELEASE.jar
2)、在配置文件中加入AOP的命名空间
xmlns:aop="http://www.springframework.org/schema/aop" http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
3)、基于注解的方式
a. 在配置文件中
<!--使AspectJ注解起作用:自动为匹配的类生成代理对象-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
b. 把横切关注点的代码抽象到切面的类中。
i. 切面首先是一个IOC中的bean,即加入@Component注解
<!--注解配置bean-->
<!--使用注解时,配置自动扫描的包-->
<context:component-scan base-package="com.atguigu.spring.aop.impl"></context:component-scan>
ii. 切面还需加入@Aspect 注解
c. 在类中声明各种通知:
i. 声明一个方法
ii. 在方法前加入@Before 注解

d. 可以在通知方法中声明一个类型为JoinPoint 的参数,然后就能访问链接细节,如方法名称和参数值。
//把这个类声明成切面:需要把该类放入到IOC容器中、再声明为一个切面
@Aspect
@Component
public class LoggingAspect {
@Before("execution(public int com.atguigu.spring.aop.impl.ArithmeticCalculator.*(int,int))")
public void beforeMethod(JoinPoint joinPoint){
String methodName = joinPoint.getSignature().getName();
List<Object> args = Arrays.asList(joinPoint.getArgs());
System.out.println("The method "+methodName+" begins with"+args);
}
}
4)、测试
public class Test_aop {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
ArithmeticCalculator arithmeticCalculator = (ArithmeticCalculator) context.getBean("arithmeticCalculatorImpl");
int add = arithmeticCalculator.add(2, 3);
System.out.println(add);
int div = arithmeticCalculator.div(9, 3);
System.out.println(div);
}
}
个人笔记:
AOP是面向切面编程,可以在原始的方法中添加功能等,原理是动态代理(自己可以了解一下代理实现的几种方式),是Spring帮我们实现的。
来源:https://www.cnblogs.com/xjs1874704478/p/11998893.html