spring-Aop by aspectj pojo+xml (2)

讲述aspectj通过pojo+xml形式表达springAop环绕通知 的demo

1 接口定义

package com.msyd.spring.aop.pojoxml;

public interface Performer {
    public void perform();
}

2 目标类定义

package com.msyd.spring.aop.pojoxml;
public class Singer implements Performer {
    public void perform() {
        System.out.println("i am a singer, i speak for myself !");
        /*String ss = null;
        ss.length();*/
    }
}

3 环绕切面定义

package com.msyd.spring.aop.pojoxml;

import org.aspectj.lang.ProceedingJoinPoint;

public class AudienceAround {

    public Object watch(ProceedingJoinPoint pjp) {
        try {
            System.out.println("takeSeat");
            System.out.println("turnOff");
            Object ret = pjp.proceed();
            System.out.println("Applaud");
            return ret;
        } catch (Throwable e) {
            System.out.println("payOff");
        } finally {
            System.out.println("goHome");
        }
        return null;
    }
}

4 xml定义

<?xml version="1.0"?>
<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/aop
     http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
        http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
    <!-- 观众:切面 -->
    <bean id="audience" class="com.msyd.spring.aop.pojoxml.AudienceAround"/>

    <!-- 目标对象 -->
    <bean id="singer" class="com.msyd.spring.aop.pojoxml.Singer"/>

    <aop:config>
       <aop:aspect id="audienceAspect" ref="audience">
           <aop:around method="watch" pointcut="execution(* *..Performer.perform(..))"/>
       </aop:aspect>

    </aop:config>

</beans>

5 测试类

package com.msyd.spring.aop.pojoxml;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AppAround {

    public static void main(String[] args) {
        ApplicationContext ac = new ClassPathXmlApplicationContext("pojoxmlAround.xml", AppAround.class);
        Performer P = (Performer) ac.getBean("singer");
        P.perform();
    }

}

6 测试结果

①无异常情况
takeSeat
turnOff
i am a singer, i speak for myself !
Applaud
goHome

②有异常情况
takeSeat
turnOff
i am a singer, i speak for myself !
payOff
goHome

到这,我抛砖引玉,做下这段时间spring Aop的切面实现之aspectj的学习小结,
spring-Aop切面,可以通过asbectj来实现,一种是 aspectj注解的形式,一种是aspectj pojo+xml 的形式,呈现 前置通知,后置通知,环绕通知以及异常通知从而来展现springAop的切面实现效果。

这里写图片描述

猜你喜欢

转载自blog.csdn.net/haidaoxianzi/article/details/80639337
今日推荐