AOP是一个比较通用的概念,主要关注的内容用一句话来说就是"如何使用一个对象代理另外一个对象",不同的框架会有不同的实现,Aspectj 是在编译期就绑定了代理对象与被代理对象的关系,而Spring是在运行期间通过动态代理的方式来现实代理对象与被代理对象的绑定.具体的概念可以参考各自的文档:

Spring: http://docs.spring.io/spring/docs/3.2.1.RELEASE/spring-framework-reference/html/aop.html#aop-introduction

Aspecctj:http://eclipse.org/aspectj/

接下来仍然通过一个综合的例子来说明使用XML的方式如何使用Spring AOP

入口类

package com.eric.introduce;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import com.eric.introduce.aop.Contestant;
import com.eric.introduce.aop.IUser;
import com.eric.introduce.aop.Worker;
import com.eric.introduce.di.Performer; public class AOPCaller { private static final String CONFIG = "com/eric/introduce/aop/aop.xml";
private static ApplicationContext context = new ClassPathXmlApplicationContext(
CONFIG); public static void main(String[] args) {
// simpleAOPCase();
// arguementAOPTest();
demoDeclareParents();
} /**
* 演示了aop after-returning/before/after-throwing/around
* NOTE:如果在performer()方法执行的过程中产生异常且在around的方法中捕获了异常
* ,则after-throwing对应的方法不会被执行
*/
public static void simpleAOPCase() {
// 必须是接口类型,否则会包ClassCastException
Performer eric = (Performer) context.getBean("performer1");
eric.performer();
} /**
* 演示:aop 参数的传递方法
* 在用户开户成功后,发送一条问候短信,通过userName参数把用户名发给SMSGreeting
*/
public static void arguementAOPTest() {
IUser user = (IUser) context.getBean("user");
user.openAccount("Eric");
} /**
* 演示aop:declare-parents 的用法
* 在不改变源码的情况下,让Worker的子类包含Contestant接口的功能.
* getBean("worker")返回的对象即可以强转成Worker也可以强转成Contestant,而该对象只是实现了Worker接口
*/
public static void demoDeclareParents() {
Worker worker = (Worker) context.getBean("worker");
worker.hardWord();
((Contestant) worker).receiveAward(); Contestant worker2 = (Contestant) context.getBean("worker");
worker2.receiveAward();
((Worker) worker2).hardWord();
} }

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-3.0.xsd"> <bean id="audience" class="com.eric.introduce.aop.Audience" />
<bean id="performer1" class="com.eric.introduce.di.InstrumentPerformer" /> <bean id="user" class="com.eric.introduce.aop.MobileUser" />
<bean id="smsgreeting" class="com.eric.introduce.aop.SMSGreeting" />
<!-- 为了使用aop:declare-parents特性,ITWorker必须声明为Worker接口的子类 -->
<bean id="worker" class="com.eric.introduce.aop.ITWorker" /> <aop:config>
<aop:aspect ref="audience">
<aop:pointcut
expression="execution(* com.eric.introduce.di.InstrumentPerformer.performer(..))"
id="performance" />
<aop:before method="takeSeat" pointcut-ref="performance" />
<aop:before method="turnOffCell" pointcut-ref="performance" />
<aop:after-returning method="applaud"
pointcut-ref="performance" />
<aop:after-throwing method="demandRefund"
pointcut-ref="performance" /> <aop:around method="calculateTime" pointcut-ref="performance" />
</aop:aspect> <aop:aspect ref="smsgreeting">
<aop:pointcut
expression="execution(* com.eric.introduce.aop.MobileUser.openAccount(String)) and args(userName)"
id="openaccount" />
<!-- 在用户开户成功后,发送一条问候短信,通过userName参数把用户名发给SMSGreeting -->
<aop:after-returning method="greeting"
pointcut-ref="openaccount" arg-names="userName" /> </aop:aspect> <aop:aspect>
<!-- 在不改变源码的情况下,让Worker的子类包含Contestant接口的功能 -->
<!-- com.eric.introduce.aop.Worker+ 说明针对Worker的子类有效 -->
<aop:declare-parents types-matching="com.eric.introduce.aop.Worker+"
implement-interface="com.eric.introduce.aop.Contestant"
default-impl="com.eric.introduce.aop.GraciousContestant" />
</aop:aspect> </aop:config> </beans>

其他相关类

after-returning/before/after-throwing/around 相关

package com.eric.introduce.aop;

import org.aspectj.lang.ProceedingJoinPoint;

/**
* 观众类
*
* @author Eric
*
*/
public class Audience {
public void takeSeat() {
System.out.println("AOP: Enter, take seat");
} public void turnOffCell() {
System.out.println("AOP: Show will start, turn off cell");
} public void applaud() {
System.out.println("AOP: Nice performance, applaud");
} public void demandRefund() {
System.out.println("AOP: Bad Performance, Return money");
} public void calculateTime(ProceedingJoinPoint joinPoint) {
long begintime = System.currentTimeMillis();
try {
joinPoint.proceed();
} catch (Throwable exception) {
System.out.println("Live Show has Exception");
} long end = System.currentTimeMillis();
System.out.println("AOP aRound: Spent Time:" + (end - begintime));
} } package com.eric.introduce.di; import java.util.List;
import java.util.Properties; /**
 * 定义一个表演者,这个表演者实现Performer接口
 *
 * @author Eric
 *
 */
public class InstrumentPerformer implements Performer {     /**
     * demo injection value
     */
    private String name;
    /**
     * demo injection Ref Bean
     */
    private Instrument instrument;     /**
     * demo injection original typ
     */
    private int age;     /**
     * demo injection internal bean
     */
    private Instrument privateInstrument;
    /**
     * demo injection List/Set/Array
     */
    private List<Fruit> favFruit;     /**
     * demo injection Properties/Map
     */
    private Properties properties;     @Override
    public void performer() {
        System.out.println("Normal Instrument:");
        try {
            Thread.sleep(1999);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        instrument.play();
        System.out.println("Special Instrument:");
        privateInstrument.play();
    }     @Override
    public void eatFruit() {
        for (Fruit fruit : favFruit) {
            fruit.eat();
        }
    }     @Override
    public void printProperties() {
        System.out.println(name + " Properties:\n");
        for (Object key : properties.keySet()) {
            System.out.println(key + " " + properties.getProperty((String) key)
                    + " \n");
        }
    }     public String getName() {
        return name;
    }     public void setName(String name) {
        this.name = name;
    }     public Instrument getInstrument() {
        return instrument;
    }     public void setInstrument(Instrument instrument) {
        this.instrument = instrument;
    }     public int getAge() {
        return age;
    }     public void setAge(int age) {
        this.age = age;
    }     public Instrument getPrivateInstrument() {
        return privateInstrument;
    }     public void setPrivateInstrument(Instrument privateInstrument) {
        this.privateInstrument = privateInstrument;
    }     public List<Fruit> getFavFruit() {
        return favFruit;
    }     public void setFavFruit(List<Fruit> favFruit) {
        this.favFruit = favFruit;
    }     public Properties getProperties() {
        return properties;
    }     public void setProperties(Properties properties) {
        this.properties = properties;
    } }  

aop:declare-parents 相关

package com.eric.introduce.aop;

/**
* 主要用来演示declare-parents
*
* @author Eric
*
*/
public interface Contestant {
public void receiveAward();
} package com.eric.introduce.aop; public class GraciousContestant implements Contestant { @Override
public void receiveAward() {
System.out.println("receiveAward was executed");
} } package com.eric.introduce.aop; public class ITWorker implements Worker {
public void hardWord() {
System.out.println("Worker is working hard!");
}
} package com.eric.introduce.aop; /**
* 主要用来演示declare-parents
*
* @author Eric
*
*/
public interface Worker {
public void hardWord();
}

参数相关

package com.eric.introduce.aop;

/**
* 定义一个问候接口
* @author Eric
*
*/
public interface IGreeting {
/**
* 定义了问候方法,但检测到有用户开户时,通过AOP机制自动发送问候短信
* @param name
*/
public void greeting(String name);
} package com.eric.introduce.aop; public interface IUser {
/**
* 开户操作
* @param name
*/
public void openAccount(String name);
} package com.eric.introduce.aop; public class MobileUser implements IUser { @Override
public void openAccount(String name) {
System.out.println("Register Succssful:" + name);
} } package com.eric.introduce.aop; /**
* 短信問候
* @author Eric
*
*/
public class SMSGreeting implements IGreeting { @Override
public void greeting(String name) {
System.out.println("Dear " + name + " Welcome to use CMCC");
} }

Spring3.0 入门进阶(三):基于XML方式的AOP使用的更多相关文章

  1. Spring3.0 入门进阶(1):从配置文件装载Bean

    Spring 已经盛行多年,目前已经处于3.0阶段,关于Spring的概念介绍性的东西网上已经很多,本系列博客主要是把一些知识点通过代码的方式总结起来,以便查阅. 作为入门,本篇主要介绍Bean的加载 ...

  2. SpringMVC入门(基于XML方式实现)

    ----------------------siwuxie095 SpringMVC 入门(基于 XML 方式实现) (一)搭建 SpringMVC 环境 1.先下载相关库文件,下载链接: (1)ht ...

  3. spring3.0使用annotation完全代替XML(三)

    很久之前写过两篇博客: spring3.0使用annotation完全代替XML spring3.0使用annotation完全代替XML(续) 用java config来代替XML,当时还遗留下一些 ...

  4. Spring-注入方式(基于xml方式)

    1.基于xml方式创建对象 <!--配置User类对象的创建 --> <bean id="user" class="com.at.spring5.Use ...

  5. Spring声明式事务管理(基于XML方式实现)

    --------------------siwuxie095                             Spring 声明式事务管理(基于 XML 方式实现)         以转账为例 ...

  6. 基于AspectJ的XML方式进行AOP开发

    -------------------siwuxie095                                 基于 AspectJ 的 XML 方式进行 AOP 开发         1 ...

  7. Spring系列之aAOP AOP是什么?+xml方式实现aop+注解方式实现aop

    Spring系列之aop aop是什么?+xml方式实现aop+注解方式实现aop 什么是AOP? AOP为Aspect Oriented Programming 的缩写,意识为面向切面的编程,是通过 ...

  8. MyBatis入门程序(基于XML配置)

    创建一个简单的MyBatis入门程序,实现对学生信息的增删改查功能(基于XML配置) 一.新建一个Java工程,导入MyBatis核心jar包.日志相关的jar包以及连接Oracle数据库所需驱动包, ...

  9. Cxf + Spring3.0 入门开发WebService

    转自原文地址:http://sunny.blog.51cto.com/182601/625540/ 由于公司业务需求, 需要使用WebService技术对外提供服务,以前没有做过类似的项目,在网上搜寻 ...

随机推荐

  1. EXT 数据按F12,F11 显示问题

    最近做关于EXT的项目,因为是刚开始接触EXT,对什么都不熟悉,所以把其他人写好的浏览页代码考过了来,换成自己需要的. 一切都做好了,然后数据不出来,就调试看,后台也出现数据了,然后就按F12调试前台 ...

  2. HDU 1280 前m大的数【哈希入门】

    题意:中文的题目= =将各种组合可能得到的和作为下标,然后因为不同组合得到的和可能是一样的, 所以再用一个数组num[]数组,就可以将相同的和都记录下来 #include<iostream> ...

  3. Task '' not found in root project '***'.

    android编译app报错:Task '' not found in root project '***'.将build.gradle里的 if (gradle.gradleVersion > ...

  4. 入门视频采集与处理(学会分析YUV数据)

    做视频采集与处理,自然少不了要学会分析YUV数据.因为从采集的角度来说,一般的视频采集芯片输出的码流一般都是YUV数据流的形式,而从视频处理(例如H.264.MPEG视频编解码)的角度来说,也是在原始 ...

  5. MVC&WebForm对照学习:ajax异步请求

    写在前面:由于工作需要,本人刚接触asp.net mvc,虽然webform的项目干过几个.但是也不是很精通.抛开asp.net webform和asp.net mvc的各自优劣和诸多差异先不说.我认 ...

  6. sqlserver能否调用webservice发送短信呢?

    上班的时候突然有一个想法,sqlserver能否调用webservice发送短信呢? 经过查找资料,终于找到了解决办法,现将步骤贴到下面: (1)开启sqlserver组件功能,如果不开启这个组件功能 ...

  7. HDU 5727 Necklace 环排+二分图匹配

    这是从山东大学巨巨那里学来的做法 枚举下黑色球的排列总数是8!,然后八个白球可选的位置与左右两个黑球存不存在关系建图就行 这是原话,具体一点,每次生成环排,只有互不影响的才连边 最后:注重一点,n个数 ...

  8. [Irving]字符串相似度-字符编辑距离算法(c#实现)

    编辑距离(Edit Distance),又称Levenshtein距离,是指两个字串之间,由一个转成另一个所需的最少编辑操作次数.许可的编辑操作包括将一个字符替换成另一个字符,插入一个字符,删除一个字 ...

  9. [python]倒计时实现

    for num in range(5,0,-1):     time.sleep(1)     sys.stdout.flush()     sys.stdout.write('\rPlease Wa ...

  10. 一幅图概括Android测试的方方面面

    一幅图概括Android测试的方方面面,来自网络: 另外的一些测试技巧 1,测试应用程序时,环境是很大的一个影响因素:系统时间,网络情况,异常关闭等 2,测试应用程序时,第三方嵌入程序也是有影响的.如 ...