Spring Aop面向切面编程

来源:互联网 发布:vip域名备案 编辑:程序博客网 时间:2024/06/02 04:39

AOP(Aspect Oriented Programming)面向切面编程,通过预编译方式和运行期动态代理实现程序功能的横向多模块统一控制的一种技术。AOP是OOP的补充,是Spring框架中的一个重要内容。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。AOP可以分为静态织入与动态织入,静态织入即在编译前将需织入内容写入目标模块中,这样成本非常高。动态织入则不需要改变目标模块。Spring框架实现了AOP,使用注解配置完成AOP比使用XML配置要更加方便与直观。
简单总结,用例:
AOP
面向切面编程,目的是降低直接的耦合性,基于动态代理模式实现;
名词:
目标对象
代理对象
通知:前置 后置 异常 最终 环绕
切入点
使用步骤:
1.添加Maven依赖
   <properties>
<spring-version>4.3.5.RELEASE</spring-version>
</properties>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring-version}</version>
</dependency>
2.在配置文件中添加schema
<?xml version="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
3.创建一个通知类:用于存放各种通知(方法)
public classAopAspect {

public voidbeforAdvice(){
System.out.println("前置通知");
}

public voidafterReturning(){
System.out.println("后置通知");
}
public voidafterThowing(){
System.out.println("异常通知");
}
public voidafter(){
System.out.println("最终通知");
}
//环绕通知
publicObject aroundAdvice(ProceedingJoinPoint joinPoint) {
Object result = null;
try{
System.out.println("前置通知");
result = joinPoint.proceed();
System.out.println("后置");
} catch(Throwable throwable) {
System.out.println("异常");
} finally{
System.out.println("最终");

}
returnresult;
}
}
3.在xml中进行配置
将类放入Spring容器

使用<aop:config>节点进行配置
aop:pointcut 切入点表达式
(指定目标对象的范围:切入点表达式)

* com.lin.service ..*.*(..) —参数列表
| | |
返回类型 本包及其自包 所有类 所有方法

aop:befoer:前置通知
aop:after-rerutning 后置通知
aop:after-throwing异常通知
aop:after:最终通知
aop:around 环绕通知


!--AOP-->
<bean id="myProxy" class="com.lin.service.myProxy"/>

<beanid="aopAspect"class="com.lin.aop.AopAspect"/>
<aop:config>
<aop:aspectref="aopAspect">
<aop:pointcutid="pointcut"
expression="execution(* com.lin.service..*.*(..))"/>
<!--环绕通知--> <!--前置通知-->
<aop:beforemethod="beforAdvice"pointcut-ref="pointcut"/>
<!--后置通知-->
<aop:after-returningmethod="afterReturning"pointcut-ref="pointcut"/>
<!--异常通知-->
<aop:after-throwingmethod="afterThowing"pointcut-ref="pointcut"/>
<!--最终通知-->
<aop:aftermethod="after"pointcut-ref="pointcut"/>
<!--环绕通知-->
<aop:aroundmethod="aroundAdvice"pointcut-ref="pointcut">

</aop:around>
</aop:aspect>
</aop:config>
原创粉丝点击