AOP为Aspect Oriented Programming的缩写,意为:面向切面编程
AOP采取横向抽取机制,取代了传统纵向继承体系重复性代码(性能监视、事务管理、安全检查、缓存)
Spring的基于AspectJ的AOP的开发
- 【被增强类可以不用实现接口】自动代理基于【切面=通知类型+切入点】
- 注解自动代理: <aop:aspectj-autoproxy/>
AspectJ的概述:
AspectJ是一个面向切面的框架,它扩展了Java语言。AspectJ定义了AOP语法所以它有一个专门的编译器用来生成遵守Java字节编码规范的Class文件。
Spring为了简化自身的AOP的开发直接将AspectJ引入到本身作为其AOP开发的使用.
Spring的基于AspectJ的注解的AOP开发:
1.所需jar包
2.applicationContext.xml开启注解配置
<aop:aspectj-autoproxy/>
3.定义切面
通知类型:
@Before 前置通知,相当于BeforeAdvice
@AfterReturning 后置通知,相当于AfterReturningAdvice
@Around 环绕通知,相当于MethodInterceptor
@AfterThrowing抛出通知,相当于ThrowAdvice
@After 最终final通知,不管是否异常,该通知都会执行
@DeclareParents 引介通知,相当于IntroductionInterceptor
切入点的表达式:
基于execution函数定义.
execution(“表达式”):
表达式语法: [访问修饰符] 方法返回值 方法名(方法参数)异常
execution(* *(..));
execution(* cn.itcast.dao.*.add*(..));
execution(* cn.itcast.dao.*(..));
execution(* cn.itcast.dao..*(..));
execution(* cn.itcast.dao.UserDao.add(..));
execution(* cn.itcast.dao.UserDao+.add(..));+代表其子类或其实现类
@Aspect public class MyAspectAnno { @Before("execution(* cn.itcast.spring.demo1.CustomerDao+.add(..))") public void before(){ System.out.println("前置通知======权限校验========="); } }
将切面类交给Spring管理:
<!-- 配置切面 --> <bean class="cn.itcast.spring.demo1.MyAspectAnno"/>
Spring的基于AspectJ的XML的AOP开发:
1.jar包可以参考上面基于注解的方式引入的jar包
2.编写切面交给spring管理
public class MyAspectXml { public void before(){ System.out.println("前置通知=============="); } }
<!-- 配置切面 --> <bean id="myAspectXml" class="cn.itcast.spring.demo2.MyAspectXml"/>
3.配置aop
<!-- 完成AOP的配置 --> <aop:config> <!-- 配置切入点 --> <aop:pointcut expression="execution(* cn.itcast.spring.demo2.OrderDao.add(..))" id="pointcut1"/> <aop:aspect ref="myAspectXml"> <aop:before method="before" pointcut-ref="pointcut1"/> </aop:aspect> </aop:config>