美文网首页
spring学习笔记aop-1

spring学习笔记aop-1

作者: cp_insist | 来源:发表于2017-01-05 20:47 被阅读0次

引言:在软件业,AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式运行期动态代理实现程序功能的统一维护的一种技术。AOP是OOP(面向对象编程)的延续,是软件开发中的一个热点,也是spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。

一:aop的实现方式;

1:使用预编译的方式实现:
Aspect
2:使用运行期动态代理的方式实现:
使用jdk的动态代理或者cglib的动态代理;主要例子有spring 的aop和jboss的aop;

二:aop的功能:

事务,日志,性能统计,安全控制,异常处理
切面是和系统功能垂直的;
业务是横向的走;切面是垂直走的;

三:和aop相关的基本概念:

  • A:切面:关注点的模块化(事务);横穿多个对象
  • B:连接点:程序执行过程中的某一个特定的点
  • C:通知:在切面的某个特定的连接点上执行的动作
    通知类型:
    前置通知:目标方法执行之前
    返回后通知:目标方法返回之后
    抛出异常后通知:抛出异常时
    后置通知:连接点退出时,无论是正常还是异常都执行
    环绕通知:包围连接点
  • D:切入点:匹配连接点的断言,在AOP中通知和一个切入点表达式关联如何在切面中匹配一个连接点
  • E:引入:在不修改代码的前提下为类添加新的方法和属性动态修改Class文件来为类增加方法或者属性
  • F:目标对象:被一个或者多个切面所通知的对象
  • J:AOP代理AOP框架创建的对象,用来实现切面契约(包括通知方法执行等功能)
  • H:织入:将切面连接到其他应用程序或者对象上,并创建一个被通知的对象,分为:编译时织入,类加载时织入,执行时织入;

四:spring中的aop具体表示:

  • 1::Spring中的AOP
    • 提供了声明式的企业服务,特别是EJB的替代服务
    • 允许用户制定自己的方面,已完成OOP和AOP的互补使用
    • 不是提供完整的AOP的实现;提供一种AOP和IOC的整合,AspectJ只一个完整的全面的AOP实现;
  • 2:spring AOP的实现方式
    有接口的和无接口的Spring AOP实现区别:
    • 有接口的用JDK的动态代理
    • 无接口的使用的CGlib的动台代理
  • 2.1:各种通知的实现:
    具体配置:在响应的xml文件中
<?xml version="1.0" encoding="UTF-8"?>
<!--xmlns表示命名空间-->
<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表示相应类所处位置-->
    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-4.0.xsd">
    <bean id="user" class="com.cp.aop.User"></bean>
    <!--切面 -->
    <bean id="moocAspect" class="com.cp.aop.aspect"></bean>
    <aop:config>
        <!--定义一个切面通知:和上面的bean相对应 -->
        <aop:aspect id="aspectA" ref="moocAspect">
            <!--定义切点通知
                这里需要注意表达式的书写: 前面那个*号别忘记;
             -->
            <aop:pointcut expression="execution(* com.cp.aop.User.add(..))" id="boforeAop"/>
            <!--前置通知 -->
            <aop:before method="before" pointcut-ref="boforeAop"/>
            <!--后置通知 -->
            <aop:after method="after" pointcut="execution(* com.cp.aop.User.add(..))"/>
            <!--异常通知 -->
            <aop:after-throwing method="throwing" pointcut-ref="boforeAop"/>
            <!--返回后通知 -->
            <aop:after-returning method="afterReturn" pointcut-ref="boforeAop"/>
            <!--环绕通知 -->
            <aop:around method="around" pointcut-ref="boforeAop"/>
            <!-- 带参数的环绕通知 -->
            <aop:pointcut id="paramter" expression="execution(* com.cp.aop.User.Aparamter(String,int)) and args(name,age)" />
            <aop:around method="aroundInit" pointcut-ref="paramter"/>
        </aop:aspect>
    </aop:config>
 </beans>

相应的类java代码:

package com.cp.aop;
import org.aspectj.lang.ProceedingJoinPoint;
public class aspect {
    public void before(){
        System.out.println("我是一个前置通知");
    }
    public void after(){
        System.out.println("我是一个后置通知");
    }
    public void afterReturn(){
        System.out.println("我是一个返回后通知");
    }
    public void throwing(){
        System.out.println("我是一个异常通知");
    }
    /**
 环绕型通知必须第一个参数必须是ProceeingJoinPoint
 @param pd
 @return
 @throws Throwable
     */
    public Object around(ProceedingJoinPoint pd) throws Throwable{
        System.out.println("我是一个环绕通知");
        Object o = pd.proceed();
        System.out.println("我是一个环绕通知");
        return o;
    }
    public void aroundInit(ProceedingJoinPoint pd,String name,int age) throws Throwable{
        System.out.println("我是一个带参数的环绕通知");
        pd.proceed(new Object[]{name,age});
        System.out.println("我是一个带参数的环绕通知");
    }
}
我们要织入的的业务位置
package com.cp.aop;
public class User {
        public void add(String str){
            System.out.println("向数据库里面插入了数据"+str);
        };
        public void Aparamter(String name,int age){
            System.out.println("我是"+name+",年级是:"+age);      
        }
}
  • 2.2:Introductions:
    允许一个切面声明一个实现指定接口的通知对象,并且提供了一个接口实现类来代表这些对象
    <aop:aspect>中的<aop:declare-parents>元素声明该元素用于声明所匹配的类型拥有一个新的parent(因此得名)
    PS:所有放到配置文件里面的aspect只支持单例的模式
<aop:config>
        <!-- 为匹配到的类型强制指定一个父类 -->
            <!--定义一个切面通知:和上面的bean相对应 -->
        <aop:aspect id ="aspectA2" ref="moocAspect">
            <aop:declare-parents 
                types-matching="com.cp.aop.User" 
                implement-interface="com.cp.aop.declare.fit"(要匹配的接口)
                default-impl="com.cp.aop.declare.fitimpl"(要匹配的实现类)
                />
        </aop:aspect>
    </aop:config>

相应的java类代码

接口
public interface fit {
    public void filter();
}
实现类
public class fitimpl implements fit{
    @Override
    public void filter() {
        System.out.println("我是一个declare-parent类型的通知");
    }
}
  • 2.3:Advisors:
    就像一个小的自包含的方面,只有一个advice;
    切面自身通过一个bean表示,并且必须实现某个advice接口,同时,advisor也可以很好的利用AspectJ的切入点表达式;
    Spring通过配置文件中<aop:advisor>元素支持advisor实际使用中,大多数情况下她会和trasactional advice配合使用;
    为了定义Advisor的优先级以便让advice可以有序,可以使用order属性来定义advisor的顺序;
    ConcurrentOperationExecutor
    相应的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-4.0.xsd">
<bean id="sevice" class="com.cp.aop.Advisor.sevice"></bean>

<bean id="ConOExecutor" class="com.cp.aop.Advisor.ConcurrentOperationExecutor">
<property name="maxRetries" value="3"></property>
<property name="order" value="100"></property>
</bean>
<aop:config>
<aop:aspect id="courrentOperationRetry" ref="ConOExecutor">
<aop:pointcut expression="execution(* com.cp.aop.Advisor.sevice.*(..))" id="idemOperation"/>
<aop:around method="doCurrentOperation" pointcut-ref="idemOperation"/>
</aop:aspect>
</aop:config>
</beans>

织入类java文件    

 +  ```
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.core.Ordered;
import org.springframework.dao.PessimisticLockingFailureException;
public class ConcurrentOperationExecutor implements  Ordered{
    private static final int  DEFAULT_MAX_RETIRIES=2;
    private int maxRetries = DEFAULT_MAX_RETIRIES;
    private int order=1;
    @Override
    public int getOrder() {
        return this.order;
    }
    public void setMaxRetries(int maxRetries) {
        this.maxRetries = maxRetries;
    }
    public int getMaxRetries() {
        return maxRetries;
    }
    public void order(int maxRetries) {
        this.maxRetries = maxRetries;
    }
    public void setOrder(int order) {
        this.order = order;
    }
    /**
     * 业务中需要对某个方法的调用次数进行控制时可以是使用
     * @param pd
     * @return
     * @throws Throwable
     */
    public Object doCurrentOperation(ProceedingJoinPoint pd) throws Throwable{
        int numAttempt = 0;
        PessimisticLockingFailureException lockingException;
        do{
            numAttempt++;
            System.out.println("尝试第"+numAttempt+"次");
            try {
                return pd.proceed();
            } catch (PessimisticLockingFailureException e) {
                // TODO Auto-generated catch block
                lockingException = e;
            }
        }while(numAttempt<=maxRetries);
        System.out.println("尝试了"+numAttempt+"次后失败了");
        throw lockingException;
    }
}
统计的方法(植入点)
public class sevice {
    public void serve(){
        System.out.println("我是一个通过Advisor");
    }
    public void Excp(){
        System.out.println("我是来让你调用失败的");
        throw new PessimisticLockingFailureException("哈哈哈哈");
    }
}

五:Spring中Aop的API:

其实就是早期的spring-aop的实现方式(没有<aop-config>之前)

a.png
  • 5.1:pointcut 织入点
    实现之一:NameMatchMethodPointcut,方法的名字进行匹配
    成员变量:mappedNames,匹配的方法名集合
  • 5.2:BeforeAdvice接口
    一个简单的通知类型,
    只是在进入方法之前被调用,不需要MethodInvocation对象
    前置通知可以在连接点执行之前插入自定义行为,但是不能改变返回值;
  • 5.3:ThrowsAdvice
    • 1:如果连接点抛出异常,throws advice在连接点返回后被调用
    • 2:如果throws-advice的方法抛出异常,那么它将覆盖原有异常
    • 3:接口org.springframework.aop.ThrowsAdvice不包含任何方法,仅仅是一个声明,实现类需要实现类似下面的方法:
      查看源代码会发现其实异常ThrowsAdvice通知里面压根就没有任何抽象方法
      其实spring内部是通过反射去匹配方法的,里面有四种方法分别是:
public void afterThrowing(Exception ex)
public void afterThrowing(RemoteException)
public void afterThrowing(Method method, Object[] args, Object target, Exception ex)
public void afterThrowing(Method method, Object[] args, Object target, ServletException ex)

实现这个接口就必须实现这四个方法中的一个

  • 5.4:afterReturningadvice;
    后置通知,必须实现org.springframework.aop.afterReturnAdvice接口;
    可以访问返回值但是不能进行修改,也可以访问被调用的方法,方法的参数和目标;
    如果抛出异常就会抛出拦截链,替代返回值;

  • 5.5:InterceptionAroundadvice:
    spring的切入点模型使得切入点可以独立与advice重用,以针对不同的advice可以使用相同的切入点;
    5.6:Introduction advice;
    spring把引入通知作为一种特殊的拦截通知;
    需要IntroductionAdvisor和IntroductionInterceptor
    仅仅适用于类,不能和任何切入点一起使用;
    introduction advisor 比较简单,持有独立的LockMixin实例

根据上面的表格,哪一种通知就实现哪一种接口即可:
具体代码就不上了:
简单说一下配置文件中的内容:

    <!--各种通知 -->
    <bean id="myBeforeAdvice" class="com.cp.aop.api.MyBeforeAdvice"></bean>
    <bean id="myAfterAdvice" class="com.cp.aop.api.MyAfterAdvice"></bean>
    <bean id="myThrowAdvice" class="com.cp.aop.api.MyThrowAdvice"></bean>
    <bean id="myMethodIntercptor" class="com.cp.aop.api.MyMethodIntercptor"></bean>
 <!-- 第一种定义了植入点的: 
    定义织入点
    <bean id="pointCutBean" class="org.springframework.aop.support.NameMatchMethodPointcut">
  要拦截目标对象的方法        
            <property name="mappedNames">
            <list>
                <value>add11*</value>
            </list>
        </property>
    </bean> 
    顾问(即包含通知或者切点)
    <bean id="defaultAdvisor" class="org.springframework.aop.support.DefaultPointcutAdvisor">
        <property name="advice" ref="myBeforeAdvice"></property>
        <property name="pointcut" ref="pointCutBean"></property>
    </bean>
   通过ProxyFactoryBean工厂创建代理对象
    <bean id="proxyUser" class="org.springframework.aop.framework.ProxyFactoryBean">
        目标对象
        <property name="target" >
            <ref bean="user1"/>
        </property>
        interceptorNames(拦截器名字集合)里面只可以配置通知或者通知者(顾问)
        <property name="interceptorNames">
            <list>
                <value>defaultAdvisor</value>
                <value>myMethodIntercptor</value>
                <value>myAfterAdvice</value>
                <value>myThrowAdvice</value>        
            </list>
        </property>
    </bean>
    -->

相关文章

网友评论

      本文标题:spring学习笔记aop-1

      本文链接:https://www.haomeiwen.com/subject/wynzvttx.html