Spring3.0 入门进阶(3):基于XML方式的AOP使用

2024-02-14 11:48

本文主要是介绍Spring3.0 入门进阶(3):基于XML方式的AOP使用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

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() {// 必须是接口类型,否则会包ClassCastExceptionPerformer 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:pointcutexpression="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:pointcutexpression="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;@Overridepublic 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();}@Overridepublic void eatFruit() {for (Fruit fruit : favFruit) {fruit.eat();}}@Overridepublic 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 {@Overridepublic 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 {@Overridepublic void openAccount(String name) {System.out.println("Register Succssful:" + name);}}package com.eric.introduce.aop;/*** 短信問候* @author Eric**/
public class SMSGreeting implements IGreeting {@Overridepublic void greeting(String name) {System.out.println("Dear " + name + " Welcome to use CMCC");}}


这篇关于Spring3.0 入门进阶(3):基于XML方式的AOP使用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/708420

相关文章

Linux中压缩、网络传输与系统监控工具的使用完整指南

《Linux中压缩、网络传输与系统监控工具的使用完整指南》在Linux系统管理中,压缩与传输工具是数据备份和远程协作的桥梁,而系统监控工具则是保障服务器稳定运行的眼睛,下面小编就来和大家详细介绍一下它... 目录引言一、压缩与解压:数据存储与传输的优化核心1. zip/unzip:通用压缩格式的便捷操作2.

使用Python实现可恢复式多线程下载器

《使用Python实现可恢复式多线程下载器》在数字时代,大文件下载已成为日常操作,本文将手把手教你用Python打造专业级下载器,实现断点续传,多线程加速,速度限制等功能,感兴趣的小伙伴可以了解下... 目录一、智能续传:从崩溃边缘抢救进度二、多线程加速:榨干网络带宽三、速度控制:做网络的好邻居四、终端交互

Python中注释使用方法举例详解

《Python中注释使用方法举例详解》在Python编程语言中注释是必不可少的一部分,它有助于提高代码的可读性和维护性,:本文主要介绍Python中注释使用方法的相关资料,需要的朋友可以参考下... 目录一、前言二、什么是注释?示例:三、单行注释语法:以 China编程# 开头,后面的内容为注释内容示例:示例:四

从入门到精通C++11 <chrono> 库特性

《从入门到精通C++11<chrono>库特性》chrono库是C++11中一个非常强大和实用的库,它为时间处理提供了丰富的功能和类型安全的接口,通过本文的介绍,我们了解了chrono库的基本概念... 目录一、引言1.1 为什么需要<chrono>库1.2<chrono>库的基本概念二、时间段(Durat

java实现docker镜像上传到harbor仓库的方式

《java实现docker镜像上传到harbor仓库的方式》:本文主要介绍java实现docker镜像上传到harbor仓库的方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录1. 前 言2. 编写工具类2.1 引入依赖包2.2 使用当前服务器的docker环境推送镜像2.2

Go语言数据库编程GORM 的基本使用详解

《Go语言数据库编程GORM的基本使用详解》GORM是Go语言流行的ORM框架,封装database/sql,支持自动迁移、关联、事务等,提供CRUD、条件查询、钩子函数、日志等功能,简化数据库操作... 目录一、安装与初始化1. 安装 GORM 及数据库驱动2. 建立数据库连接二、定义模型结构体三、自动迁

python删除xml中的w:ascii属性的步骤

《python删除xml中的w:ascii属性的步骤》使用xml.etree.ElementTree删除WordXML中w:ascii属性,需注册命名空间并定位rFonts元素,通过del操作删除属... 可以使用python的XML.etree.ElementTree模块通过以下步骤删除XML中的w:as

ModelMapper基本使用和常见场景示例详解

《ModelMapper基本使用和常见场景示例详解》ModelMapper是Java对象映射库,支持自动映射、自定义规则、集合转换及高级配置(如匹配策略、转换器),可集成SpringBoot,减少样板... 目录1. 添加依赖2. 基本用法示例:简单对象映射3. 自定义映射规则4. 集合映射5. 高级配置匹

Spring 框架之Springfox使用详解

《Spring框架之Springfox使用详解》Springfox是Spring框架的API文档工具,集成Swagger规范,自动生成文档并支持多语言/版本,模块化设计便于扩展,但存在版本兼容性、性... 目录核心功能工作原理模块化设计使用示例注意事项优缺点优点缺点总结适用场景建议总结Springfox 是

嵌入式数据库SQLite 3配置使用讲解

《嵌入式数据库SQLite3配置使用讲解》本文强调嵌入式项目中SQLite3数据库的重要性,因其零配置、轻量级、跨平台及事务处理特性,可保障数据溯源与责任明确,详细讲解安装配置、基础语法及SQLit... 目录0、惨痛教训1、SQLite3环境配置(1)、下载安装SQLite库(2)、解压下载的文件(3)、