spring学习笔记aop-1

2017-01-05  本文已影响0人  cp_insist

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

一:aop的实现方式;

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

二:aop的功能:

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

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

四:spring中的aop具体表示:

<?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);      
        }
}
<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类型的通知");
    }
}

<?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
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)

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

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

    <!--各种通知 -->
    <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>
    -->

上一篇下一篇

猜你喜欢

热点阅读