spring aop 笔记

AOP使用

AOP:代码的切面思想
用处:对业务逻辑各个部分进行隔离
好处:降低耦合度,提高程序的重用性
主要场景:日志记录,性能统计,安全控制,事务处理,异常处理
SpringAOP术语
  1. 目标类(目标对象)tager
  2. 代理类(代理对象)proxy
  3. 目标对象上的方法(连接点)joinpoint
  4. 需要做事的方法(切入点)pointcut
  5. 通知(增强)advice
  6. 切面=通知+切入点 aspect、advisor
  7. 织入(切入)weaving
切入点表达式的语法
1. execution():  代表切入方式,固定语法
2. public: 方法的修饰符,通常为public方法
3. void: 方法的返回值。可以使用通配符: *, java.lang.String(完整的包名)
4. cn.sm1234.service.impl: 类所在的包
      4.1 可以使用通配符:  *  (* 只能匹配一级目录)
      4.2 可以使用 *..* 匹配任意级目录
5.CustomerServiceImpl: 类名称
      5.1 可以使用通配符:  *  (匹配任意字符)
6. save() : 代表方法
      6.1 可以使用通配符:  *  (匹配任意字符) 
7.  方法的参数
      7.1 可以使用通配符: ..  (匹配任何参数类型的方法)
通知类型
1. 前置通知 before
xml:<aop:before method="before" pointcut-ref="pt"/>
注解:@Before(value = "execution(....)")
在方法的前面执行
2. 最终通知 after
xml:<aop:after method="after" pointcut-ref="pt"/>
注解:@After(value = "execution(....)")
在方法的最后执行,无论方法是否出现异常,通知都会被执行 
3. 后置通知 after-returning
xml:<aop:after-returning method="afterReturning" pointcut-ref="pt"/>
注解:@AfterReturning(value = "execution(....)")
在方法的最后执行,只有在方法成功执行之后才被执行 
4. 异常通知 after-throwing
xml:<aop:after-throwing method="afterThrowing" pointcut-ref="pt"/>
注解:@AfterThrowing(value = "execution(....)")
在方法出现异常的时候执行
5. 环绕通知 around
xml:<aop:around method="around" pointcut-ref="pt"/>
注解:@Around(value = "execution(....)")
在方法的前后执行
SpringAOP的XML方式

aspectJ插件,作用是简化SpringAOP的XML方式

  1. 目标类(目标对象)tager
<bean id="customerService" class="cn.sm1234.service.impl.CustomerServiceImpl"/>

public class CustomerServiceImpl implements CustomerService
..............
  1. 通知(增强)advice
<bean id="myAspect1" class="cn.sm1234.apsect.MyAspect1"/>
public class MyAspect1
..............
  1. 切面=通知+切入点 aspect、advisor
	<aop:config>
		<!-- 切面 = 通知+切入点 -->
		<aop:aspect ref="myAspect1">
		    <!-- 前置切入 -->
			<aop:before method="log" pointcut-ref="pt"/>
			<aop:pointcut expression="execution(public void cn.sm1234.service.impl.CustomerServiceImpl.*())" id="pt"/>
		</aop:aspect>
	</aop:config>
SpringAOP的注解方式
  1. 目标类(目标对象)tager
<bean id="customerService" class="cn.sm1234.service.impl.CustomerServiceImpl"/>

public class CustomerServiceImpl implements CustomerService
..............
  1. 通知(增强)advice
<bean id="myAspect" class="cn.sm1234.apsect.MyAspect"/>
@Aspect
public class MyAspect 
..............
  1. 切面=通知+切入点 aspect、advisor
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
SpringAOP的0配置方式
  1. 配置类
@Configurable
@ComponentScan(basePackages="cn.sm1234")   // 扫描指定的包
@EnableAspectJAutoProxy  // 开启AOP注解功能
public class SpringConfig 
..............
  1. 目标类(目标对象)tager
@Service
public class CustomerServiceImpl implements CustomerService 
..............
  1. 通知(增强)advice
@Component
@Aspect
public class MyAspect 
..............
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值