什么是AOP:
面向切面编程(AOP)和面向对象编程(OOP)类似,也是一种编程模式。Spring AOP 是基于 AOP 编程模式的一个框架,它的使用有效减少了系统间的重复代码,达到了模块间的松耦合目的。
AOP重要组成
切面(Aspect) 切入点和通知的结合。
连接点(Joinpoint) 指那些被拦截到的点,在 Spring 中,可以被动态代理拦截目标类的方法。
通知(Advice) 指拦截到 Joinpoint 之后要做的事情,即对切入点增强的内容。
切入点(Pointcut) 指要对哪些 Joinpoint 进行拦截,即被拦截的连接点。
Target(目标) 指代理的目标对象。
Weaving(植入) 指把增强代码应用到目标上,生成代理对象的过程。
Proxy(代理) 指生成的代理对象。
引入(Introduction)
实例:
注解方式:
xml配置:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="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.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="loggingAspect" class="org.scxh.mgrhouse.aspects.LoggingAspect"/>
<bean id="owner" class="org.scxh.mgrhouse.services.OwnerServiceImpl"/>
<!--
默认的springAop是一种基于JDK的接口代理,也就是业务逻辑实例一定要有接口
SpringAOP的aspectj也支持类的代理,也就是业务逻辑不需要接口,这是这个节点propxy-target-class一定设置为true
-->
<aop:aspectj-autoproxy proxy-target-class="true"/>
</beans>
运行结果: