AOP(Aspect-Orinted Programming)
为什么要使用AOP?
- 优点:
1.代码重用性
2.解耦业务逻辑与非业务逻辑
AOP术语:
- Aspect: 日志,安全等功能
- Join point: 函数执行或者属性访问
- Advice: 在某个函数执行点上要执行的切面功能
- Pointcut:匹配横切目标函数的表达式
Spring AOP:
- 非完整AOP
- 整合AOP与IoC
实现AOP的方式:
- XML schema-based AOP
- @AspectJ annotation-based AOP
@AspectJ annotation-based AOP(依赖AspectJWeaver)
- 添加配置
<aop:aspectj-autoproxy/>
- 需要修改Spring配置文件中的xmlns的地址,需要添加:
xmlns:aop="http://www.springframework.org/schema/aop"
- schemaLocation添加:
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
示例(@AspectJ Annotation-based AOP)
首先创建一个类 Caculator
public class Caculator {
public int add(int a,int b){
return a + b;
}
public int sub(int a,int b){
return a - b;
}
}
创建Aspect类
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
@Aspect
public class CaculatorAspect {
@AfterReturning("execution(* Caculator.* (..))")
public void doAdd(JoinPoint jp){
System.out.println("加法运算被执行了!");
}
}
编写Spring XML配置文件
<!--定义caculator Bean-->
<bean id="caculator" class="com.huyunhe.Caculator"></bean>
<!--定义Aspect Bean-->
<bean id="caculatorAspect" class="com.huyunhe.CaculatorAspect"></bean>
编写测试类
public class Test {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Application-context.xml");
Caculator caculator = context.getBean("caculator",Caculator.class);
System.out.println(caculator.add(1,2));
}
}
运行结果如下:
二月 08, 2018 8:44:05 下午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@2e5d6d97: startup date [Thu Feb 08 20:44:05 CST 2018]; root of context hierarchy
二月 08, 2018 8:44:05 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [Application-context.xml]
加法运算被执行了!
3
Process finished with exit code 0
XML Schema-based AOP 示例
编写xml配置文件
<aop:config>
<!--定义Aspect-->
<aop:aspect id="caculatorAspect" ref="caculatorAspect">
<!--定义Pointcut-->
<aop:pointcut id="caculatorPointcut" expression="execution(* com.huyunhe.Caculator.sub(..))"/>
<!--定义Advice-->
<aop:after-returning pointcut-ref="caculatorPointcut" method="doAdd"/>
</aop:aspect>
</aop:config>