AOP使用
AOP:代码的切面思想
用处:对业务逻辑各个部分进行隔离
好处:降低耦合度,提高程序的重用性
主要场景:日志记录,性能统计,安全控制,事务处理,异常处理
SpringAOP术语
- 目标类(目标对象)tager
- 代理类(代理对象)proxy
- 目标对象上的方法(连接点)joinpoint
- 需要做事的方法(切入点)pointcut
- 通知(增强)advice
- 切面=通知+切入点 aspect、advisor
- 织入(切入)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方式
- 目标类(目标对象)tager
<bean id="customerService" class="cn.sm1234.service.impl.CustomerServiceImpl"/>
public class CustomerServiceImpl implements CustomerService
..............
- 通知(增强)advice
<bean id="myAspect1" class="cn.sm1234.apsect.MyAspect1"/>
public class MyAspect1
..............
- 切面=通知+切入点 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的注解方式
- 目标类(目标对象)tager
<bean id="customerService" class="cn.sm1234.service.impl.CustomerServiceImpl"/>
public class CustomerServiceImpl implements CustomerService
..............
- 通知(增强)advice
<bean id="myAspect" class="cn.sm1234.apsect.MyAspect"/>
@Aspect
public class MyAspect
..............
- 切面=通知+切入点 aspect、advisor
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
SpringAOP的0配置方式
- 配置类
@Configurable
@ComponentScan(basePackages="cn.sm1234") // 扫描指定的包
@EnableAspectJAutoProxy // 开启AOP注解功能
public class SpringConfig
..............
- 目标类(目标对象)tager
@Service
public class CustomerServiceImpl implements CustomerService
..............
- 通知(增强)advice
@Component
@Aspect
public class MyAspect
..............