面向切面编程(Spring AOP)

一、什么是AOP

AOP即面向切面编程,通过预编译方式和运行期动态代理实现程序功能的同一维护的一种技术。主要体现在日志记录、性能统计、安全控制、事务处理和异常处理等。

1.相关概念

二、切面、切入点配置

切面相当于一个功能的某一个类,切入点是这个类的某部分,执行到切入点时需要额外执行其他代码块,执行的代码块在引用切入点时指定。

1.切面aspect

代码示例:

<?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:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
     http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
     http://www.springframework.org/schema/aop
     http://www.springframework.org/schema/aop/spring-aop-4.1.xsd">
    
    <bean id="aspect1" class="com.yh.aop.schema.advice.myAspect.Aspect1"></bean>
    
    <aop:config>
        <aop:aspect id="MyAspectAOP" ref="aspect1">
        </aop:aspect>
    </aop:config>

</beans>

2.切入点pointcut

相关规则:

 代码示例:

<?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:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
     http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
     http://www.springframework.org/schema/aop
     http://www.springframework.org/schema/aop/spring-aop-4.1.xsd">
    
    <bean id="aspect1" class="com.yh.aop.schema.advice.myAspect.Aspect1"></bean>
    
    <aop:config>
        <aop:aspect id="MyAspectAOP" ref="aspect1">
            <aop:pointcut expression="execution(com.yh.aop.schema.advice.myAspect.Aspect1.*(..))" id="pointcut1"/>
        </aop:aspect>
    </aop:config>

</beans>        

三、advice配置

1.advice的类型

猜你喜欢

转载自www.cnblogs.com/YeHuan/p/11106956.html