spring入门专题二—(aop面向切面)

什么是aop

1:AOP:Aspect Oriented Programming 的缩写,意思为面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。
2:主要的功能是:日志记录,性能统计,安全控制,事务处理,异常处理等等。

AOP的实现方式

1预编译(Aspectj)
2运行期动态代理(JDK的动态代理,CGLIB动态代理)(SpringAOP,JBoosAOP)


image.png

通知的类型:

image.png

Spring框架中AOP的作用

1:提供了声明式的企业服务,特别是EJB的替代服务的声明
2:允许用户定制自己的方面,已完成oop与Aop的互补作用


image.png

image.png

基于配置的AOP实现

image.png

声明一个切面

image.png

上图的意思为把id为aBean的bean作为一个切面声明,切面的id为myAspect

声明一个切入点

(springAOP和Aspectj都支持的)

image.png

(springAOP支持的)

image.png

等等其他的,具体使用的时候可以查阅相关的切入点表达式
例子:

<bean id="moocAspect" class="com.imooc.aop.schema.advice.MoocAspect"></bean>

<bean id="aspectBiz" class="com.imooc.aop.schema.advice.biz.AspectBiz"></bean>

<aop:config>
    <aop:aspect id="moocAspectAOP" ref="moocAspect">
        <aop:pointcut expression="execution(* com.imooc.aop.schema.advice.biz.*Biz.*(..))" id="moocPiontcut"/>

    </aop:aspect>
</aop:config>

通知advice

前置通知

image.png

返回后通知

image.png

异常后通知

image.png

最后通知(无论有无异常,最后都会执行)

image.png

环绕通知

image.png

环绕通知携带参数

image.png

image.png
<bean id="moocAspect" class="com.imooc.aop.schema.advice.MoocAspect"></bean>
    
    <bean id="aspectBiz" class="com.imooc.aop.schema.advice.biz.AspectBiz"></bean>
    
    <aop:config>
        <aop:aspect id="moocAspectAOP" ref="moocAspect">
          <aop:pointcut expression="execution(* com.imooc.aop.schema.advice.biz.*Biz.*(..))" id="moocPiontcut"/>切入点表达式
          //<aop:before method="before" pointcut-ref="moocPiontcut"/>前置通知,方法为before
          //<aop:after-returning method="afterReturning" pointcut-ref="moocPiontcut"/>返回后通知 
          //<aop:after-throwing method="afterThrowing" pointcut-ref="moocPiontcut"/> 异常后通知
          //<aop:after method="after" pointcut-ref="moocPiontcut"/> 最后通知
          //<aop:around method="around" pointcut-ref="moocPiontcut"/> 环绕通知
            
          //<aop:around method="aroundInit" pointcut="execution(* com.imooc.aop.schema.advice.biz.AspectBiz.init(String, int))  
                            and args(bizName, times)"/>
          //<aop:declare-parents types-matching="com.imooc.aop.schema.advice.biz.*(+)" 
                            implement-interface="com.imooc.aop.schema.advice.Fit"
                            default-impl="com.imooc.aop.schema.advice.FitImpl"/>
        </aop:aspect>
    </aop:config>

环绕通知:

public Object around(ProceedingJoinPoint pjp) {
        Object obj = null;
        try {
            System.out.println("MoocAspect around 1.");执行前操作
            obj = pjp.proceed();方法
            System.out.println("MoocAspect around 2.");执行后操作
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return obj;
    }

环绕通知携带参数:

public Object aroundInit(ProceedingJoinPoint pjp, String bizName, int times) {
        System.out.println(bizName + "   " + times);
        Object obj = null;
        try {
            System.out.println("MoocAspect aroundInit 1.");
            obj = pjp.proceed();
            System.out.println("MoocAspect aroundInit 2.");
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return obj;
    }

Introductions
简介允许一个切面声明一个实现指定接口的通知对象 ,并且提供一个接口实现类来代表这些对象
由<aop:aspect>中的<aop:declare-parents>元素声明该元素用于声明所匹配的类型拥有一个新的parent(因此得名)


image.png

types-matching匹配的类型
implement-interface实现的接口
default-impl接口实现类

public interface Fit {
    
    void filter();

}
public class FitImpl implements Fit {

    @Override
    public void filter() {
        System.out.println("FitImpl filter.");
    }

}
@Test
    public void testFit() {
        Fit fit = (Fit)super.getBean("aspectBiz");
        fit.filter();
    }为这个类aspectBiz的强制指定一个父类为FitImpl 
所有配置式的aspect只支持单例
image.png
image.png

使用事务的时候经常用到
例子:
配置文件

    <context:component-scan base-package="com.imooc.aop.schema"></context:component-scan>

    <aop:config>
        <aop:aspect id="concurrentOperationRetry" ref="concurrentOperationExecutor">
            <aop:pointcut id="idempotentOperation"
                expression="execution(* com.imooc.aop.schema.advisors.service.*.*(..)) " />
<!--                expression="execution(* com.imooc.aop.schema.service.*.*(..)) and -->
<!--                                @annotation(com.imooc.aop.schema.Idempotent)" /> -->
            <aop:around pointcut-ref="idempotentOperation" method="doConcurrentOperation" />
        </aop:aspect>
    </aop:config>
    
    <bean id="concurrentOperationExecutor" class="com.imooc.aop.schema.advisors.ConcurrentOperationExecutor">
        <property name="maxRetries" value="3" />
        <property name="order" value="100" />
    </bean>

public class ConcurrentOperationExecutor implements Ordered {

    private static final int DEFAULT_MAX_RETRIES = 2;

    private int maxRetries = DEFAULT_MAX_RETRIES;
    
    private int order = 1;

    public void setMaxRetries(int maxRetries) {
        this.maxRetries = maxRetries;
    }

    public int getOrder() {
        return this.order;
    }

    public void setOrder(int order) {
        this.order = order;
    }

    public Object doConcurrentOperation(ProceedingJoinPoint pjp) throws Throwable {
        int numAttempts = 0;
        PessimisticLockingFailureException lockFailureException;
        do {
            numAttempts++;
            System.out.println("Try times : " + numAttempts);
            try {
                return pjp.proceed();
            } catch (PessimisticLockingFailureException ex) {
                lockFailureException = ex;
            }
        } while (numAttempts <= this.maxRetries);
        System.out.println("Try error : " + numAttempts);
        throw lockFailureException;
    }
}

Service类

@Service
public class InvokeService {
    
    public void invoke() {
        System.out.println("InvokeService ......");
    }
    
    public void invokeException() {
        throw new PessimisticLockingFailureException("");
    }

}

测试类:

@RunWith(BlockJUnit4ClassRunner.class)
public class TestAOPSchemaAdvisors extends UnitTestBase {
    
    public TestAOPSchemaAdvisors() {
        super("classpath:spring-aop-schema-advisors.xml");
    }
    
    @Test
    public void testSave() {
        InvokeService service = super.getBean("invokeService");
        service.invoke();
        
        System.out.println();
        service.invokeException();
    }

}

执行结果

image.png

第一次成功不再进行循环,第二次循环。

Spring Aop api

image.png

image.png

image.png
public class MoocBeforeAdvice implements MethodBeforeAdvice {

    @Override
    public void before(Method method, Object[] args, Object target)
            throws Throwable {
        System.out.println("MoocBeforeAdvice : " + method.getName() + "     " + 
                 target.getClass().getName());
    }

}
image.png

image.png
public class MoocThrowsAdvice implements ThrowsAdvice {
    
    public void afterThrowing(Exception ex) throws Throwable {
        System.out.println("MoocThrowsAdvice afterThrowing 1");
    }
    
    public void afterThrowing(Method method, Object[] args, Object target, Exception ex) throws Throwable {
        System.out.println("MoocThrowsAdvice afterThrowing 2 : " + method.getName() + "       " + 
                target.getClass().getName());
    }
image.png
public class MoocAfterReturningAdvice implements AfterReturningAdvice {

    @Override
    public void afterReturning(Object returnValue, Method method,
            Object[] args, Object target) throws Throwable {
        System.out.println("MoocAfterReturningAdvice : " + method.getName() + "     " + 
            target.getClass().getName() + "       " + returnValue);
    }

}
image.png
public class MoocMethodInterceptor implements MethodInterceptor {

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        System.out.println("MoocMethodInterceptor 1 : " + invocation.getMethod().getName() + "     " + 
                invocation.getStaticPart().getClass().getName());
         Object obj = invocation.proceed();
         System.out.println("MoocMethodInterceptor 2 : " + obj);
         return obj;
    }

}
image.png

image.png

image.png

image.png
public interface Lockable {
    
    void lock();

    void unlock();

    boolean locked();

}
public class LockMixin extends DelegatingIntroductionInterceptor implements Lockable {

    private static final long serialVersionUID = 6943163819932660450L;
    
    private boolean locked;

    public void lock() {
        this.locked = true;
    }

    public void unlock() {
        this.locked = false;
    }

    public boolean locked() {
        return this.locked;
    }

    public Object invoke(MethodInvocation invocation) throws Throwable {
        if (locked() && invocation.getMethod().getName().indexOf("set") == 0) {
            throw new RuntimeException();
        }
        return super.invoke(invocation);
    }

}
public class LockMixinAdvisor extends DefaultIntroductionAdvisor {

    private static final long serialVersionUID = -171332350782163120L;

    public LockMixinAdvisor() {
        super(new LockMixin(), Lockable.class);
    }
}
image.png

springAOP代理的核心类

image.png

foo引用ProxyFactoryBean,得到的对象是getOpject()方法创建的


image.png
image.png
image.png

创建一个基于接口的代理,getOpject()方法返回的就是target


image.png

配置:

<?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:context="http://www.springframework.org/schema/context"
    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/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop.xsd">
        
     <bean id="moocBeforeAdvice" class="com.imooc.aop.api.MoocBeforeAdvice"></bean>
     
     <bean id="moocAfterReturningAdvice" class="com.imooc.aop.api.MoocAfterReturningAdvice"></bean>
     
     <bean id="moocMethodInterceptor" class="com.imooc.aop.api.MoocMethodInterceptor"></bean>
     
     <bean id="moocThrowsAdvice" class="com.imooc.aop.api.MoocThrowsAdvice"></bean>
     
     
     
<!--     <bean id="bizLogicImplTarget" class="com.imooc.aop.api.BizLogicImpl"></bean> -->

<!--    <bean id="pointcutBean" class="org.springframework.aop.support.NameMatchMethodPointcut"> -->
<!--        <property name="mappedNames"> -->
<!--            <list> -->
<!--                <value>sa*</value> -->
<!--            </list> -->
<!--        </property> -->
<!--    </bean> -->
    
<!--    <bean id="defaultAdvisor" class="org.springframework.aop.support.DefaultPointcutAdvisor"> -->
<!--        <property name="advice" ref="moocBeforeAdvice" /> -->
<!--        <property name="pointcut" ref="pointcutBean" /> -->
<!--    </bean> -->
    
<!--    <bean id="bizLogicImpl" class="org.springframework.aop.framework.ProxyFactoryBean"> -->
<!--        <property name="target"> -->
<!--            <ref bean="bizLogicImplTarget"/> -->
<!--        </property> -->
<!--        <property name="interceptorNames"> -->
<!--            <list> -->
<!--                <value>defaultAdvisor</value> -->
<!--                <value>moocAfterReturningAdvice</value> -->
<!--                <value>moocMethodInterceptor</value> -->
<!--                <value>moocThrowsAdvice</value> -->
<!--            </list> -->
<!--        </property> -->
<!--    </bean>   -->
        
        

<!--    <bean id="bizLogicImplTarget" class="com.imooc.aop.api.BizLogicImpl"></bean> -->

<!--    <bean id="bizLogicImpl" class="org.springframework.aop.framework.ProxyFactoryBean"> -->
<!--        <property name="proxyInterfaces"> -->
<!--            <value>com.imooc.aop.api.BizLogic</value> -->
<!--        </property> -->
<!--        <property name="target"> -->
<!--            <bean class="com.imooc.aop.api.BizLogicImpl"></bean> -->
<!--            <ref bean="bizLogicImplTarget"/> -->
<!--        </property> -->
<!--        <property name="interceptorNames"> -->
<!--            <list> -->
<!--                <value>moocBeforeAdvice</value> -->
<!--                <value>moocAfterReturningAdvice</value> -->
<!--                <value>moocMethodInterceptor</value> -->
<!--                <value>moocThrowsAdvice</value> -->
<!--                <value>mooc*</value> -->
<!--            </list> -->
<!--        </property> -->
<!--    </bean>   -->




    <bean id="baseProxyBean" class="org.springframework.aop.framework.ProxyFactoryBean" 
            lazy-init="true" abstract="true"></bean>
    
    <bean id="bizLogicImpl"  parent="baseProxyBean">
        <property name="target">
            <bean class="com.imooc.aop.api.BizLogicImpl"></bean>
        </property>
        <property name="proxyInterfaces">
            <value>com.imooc.aop.api.BizLogic</value>
        </property>
        <property name="interceptorNames">
            <list>
                <value>moocBeforeAdvice</value>
                <value>moocAfterReturningAdvice</value>
                <value>moocMethodInterceptor</value>
                <value>moocThrowsAdvice</value>
            </list>
        </property>
    </bean>

 </beans>

实现bean:

public class BizLogicImpl implements BizLogic {
    
    public String save() {
        System.out.println("BizLogicImpl : BizLogicImpl save.");
        return "BizLogicImpl save.";
//      throw new RuntimeException();
    }

}

接口:

public interface BizLogic {
    
    String save();

}

测试类:

@RunWith(BlockJUnit4ClassRunner.class)
public class TestAOPAPI extends UnitTestBase {
    
    public TestAOPAPI() {
        super("classpath:spring-aop-api.xml");
    }
    
    @Test
    public void testSave() {
        BizLogic logic = (BizLogic)super.getBean("bizLogicImpl");
        logic.save();
    }

}

打印结果:

image.png
image.png
image.png
image.png
image.png

实现Interceptor的拦截器。

image.png
image.png
image.png
image.png
image.png

Aspectj

image.png

Aspectj的两种方式

image.png
image.png
image.png
image.png

切入点定义方式

image.png
public class MoocAspect {
    
    @Pointcut("execution(* com.imooc.aop.aspectj.biz.*Biz.*(..))")
//biz结尾的方法
    public void pointcut() {}
    //包下的任何类
    @Pointcut("within(com.imooc.aop.aspectj.biz.*)")
    public void bizPointcut() {}
}              

image.png
image.png
image.png
image.png

image.png
image.png
image.png
image.png
@Component
@Aspect
public class MoocAspect {
    
    @Pointcut("execution(* com.imooc.aop.aspectj.biz.*Biz.*(..))")
    public void pointcut() {}
    
    @Pointcut("within(com.imooc.aop.aspectj.biz.*)")
    public void bizPointcut() {}
    
    @Before("pointcut()")
    public void before() {
        System.out.println("Before.");
    }
    
    @Before("pointcut() && args(arg)")
    public void beforeWithParam(String arg) {
        System.out.println("BeforeWithParam." + arg);
    }
    
    @Before("pointcut() && @annotation(moocMethod)")
    public void beforeWithAnnotaion(MoocMethod moocMethod) {
        System.out.println("BeforeWithAnnotation." + moocMethod.value());
    }
    
    @AfterReturning(pointcut="bizPointcut()", returning="returnValue")
    public void afterReturning(Object returnValue) {
        System.out.println("AfterReturning : " + returnValue);
    }
    
    @AfterThrowing(pointcut="pointcut()", throwing="e")
    public void afterThrowing(RuntimeException e) {
        System.out.println("AfterThrowing : " + e.getMessage());
    }
    
    @After("pointcut()")
    public void after() {
        System.out.println("After.");
    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("Around 1.");
        Object obj = pjp.proceed();
        System.out.println("Around 2.");
        System.out.println("Around : " + obj);
        return obj;
    }
    
}

@Service
public class MoocBiz {
    
    @MoocMethod("MoocBiz save with MoocMethod.")
    public String save(String arg) {
        System.out.println("MoocBiz save : " + arg);
//      throw new RuntimeException(" Save failed!");
        return " Save success!";
    }

} 
image.png
image.png
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,457评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,837评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,696评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,183评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,057评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,105评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,520评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,211评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,482评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,574评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,353评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,897评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,489评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,683评论 2 335

推荐阅读更多精彩内容