spring之AOP

springAop是什么?

切面编程,就是在你项目原有的功能基础上,通过AOP去添加新的功能,这些功能是建立在原有功能的基础上的,而且原有的功能并不知道你已经添加了新的功能。比如说,你去ATM取钱,取钱是一个功能,取完钱后向你的手机发送一条取钱信息,这就是新加的功能。

在这里插入图片描述

Aop的概念

1) Aspect :切面,切入系统的一个切面。比如事务管理是一个切面,权限管理也是一个切面;

2) Join point :连接点,也就是可以进行横向切入的位置;

3) Advice :通知,切面在某个连接点执行的操作(分为: Before advice , After returning advice , After throwing advice , After (finally) advice , Around advice );

4) Pointcut :切点,符合切点表达式的连接点,也就是真正被切入的地方;

核心

AOP中关键性概念
连接点(Joinpoint):程序执行过程中明确的点,如方法的调用,或者异常的抛出.

目标(Target):被通知(被代理)的对象
注1:完成具体的业务逻辑

通知(Advice):在某个特定的连接点上执行的动作,同时Advice也是程序代码的具体实现,例如一个实现日志记录的代码(通知有些书上也称为处理)
注2:完成切面编程

代理(Proxy):将通知应用到目标对象后创建的对象(代理=目标+通知),
例子:外科医生+护士
注3:只有代理对象才有AOP功能,而AOP的代码是写在通知的方法里面的

切入点(Pointcut):多个连接点的集合,定义了通知应该应用到那些连接点。
(也将Pointcut理解成一个条件 ,此条件决定了容器在什么情况下将通知和目标组合成代理返回给外部程序)

适配器(Advisor):适配器=通知(Advice)+切入点(Pointcut)

如何实现AOP
目标对象只负责业务逻辑代码
通知对象负责AOP代码,这二个对象都没有AOP的功能,只有代理对象才有

工具类

org.springframework.aop.framework.ProxyFactoryBean用来创建一个代理对象,在一般情况下它需要注入以下三个属性:
proxyInterfaces:代理应该实现的接口列表(List)
interceptorNames:需要应用到目标对象上的通知Bean的名字。(List)
target:目标对象 (Object)

spring-context.xml


	<!-- AOP 的知识点 -->
	<!-- 目标 -->
	<bean id="bookBiz" class="com.hu.aop.biz.impl.BookBizImpl"></bean>
	<!-- 通知 -->
	<bean id="myMethodBeforeAdvice" class="com.hu.aop.advice.MyMethodBeforeAdvice"></bean>
	<bean id="myAfterReturningAdvice" class="com.hu.aop.advice.MyAfterReturningAdvice"></bean>
	<bean id="myMethodInterceptor" class="com.hu.aop.advice.MyMethodInterceptor"></bean>
	<bean id="myThrowsAdvice" class="com.hu.aop.advice.MyThrowsAdvice"></bean>
	
	<!-- 过滤通知 -->
	<bean id="MyRegexpMethodPointcutAdvisor" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
		<!-- 设置规则 -->
		<property name="advice" ref="myAfterReturningAdvice"></property>
		<!-- <property name="pattern" value=".*buy"></property> -->
		<!-- 多种条件 -->
		<property name="patterns">
			<list>
				<value>.*buy</value>
			</list>
		</property>
	</bean>
	
	<!-- 代理对象=目标+通知 -->
	<bean id="bookBizProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
		<!-- 目标 -->
		<property name="target" ref="bookBiz"></property>
		<!-- 代理的接口 -->
		<property name="proxyInterfaces">
			<!-- 目标实现的接口 -->
			<value>com.hu.aop.biz.IBookBiz</value>
		</property>
		<!-- 通知 -->
		<property name="interceptorNames">
			<list>
				<value>myMethodBeforeAdvice</value>
				<!-- <value>myAfterReturningAdvice</value> -->
				<value>MyRegexpMethodPointcutAdvisor</value>
				<value>myMethodInterceptor</value>
				<value>myThrowsAdvice</value>
			</list>
		</property>
	</bean>
	

购买的接口

public interface IBookBiz {
	// 购书
	public boolean buy(String userName, String bookName, Double price);

	// 发表书评
	public void comment(String userName, String comments);
}

我们的目标继承这个接口

public class BookBizImpl implements IBookBiz {

	public BookBizImpl() {
		super();
	}

	public boolean buy(String userName, String bookName, Double price) {
		// 通过控制台的输出方式模拟购书
		if (null == price || price <= 0) {
			throw new PriceException("book price exception");
		}
		System.out.println(userName + " buy " + bookName + ", spend " + price);
		return true;
	}

	public void comment(String userName, String comments) {
		// 通过控制台的输出方式模拟发表书评
		System.out.println(userName + " say:" + comments);
	}

}

异常处理

public class PriceException extends RuntimeException {

	public PriceException() {
		super();
	}

	public PriceException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
		super(message, cause, enableSuppression, writableStackTrace);
	}

	public PriceException(String message, Throwable cause) {
		super(message, cause);
	}

	public PriceException(String message) {
		super(message);
	}

	public PriceException(Throwable cause) {
		super(cause);
	}
	
}

前置通知

就是在我们执行一个方法的前面先执行另一个方法,
(org.springframework.aop.MethodBeforeAdvice):在连接点之前执行的通知()
案例:在购书系统当中使用AOP方式实现日志系统

public class MyMethodBeforeAdvice implements MethodBeforeAdvice {

	@Override
	public void before(Method arg0, Object[] arg1, Object arg2) throws Throwable {
		String methodName = arg0.getName();
		String clzName = arg2.getClass().getName();
		String params = Arrays.toString(arg1);
//		syso(添加日志)
//		dao.addLog(className,methodName,args,time,longTime)
		System.out.println("【系统日志】:"+clzName+"."+methodName+"("+params+")");

	}

}

后置通知

(org.springframework.aop.AfterReturningAdvice):在连接点正常完成后执行的通知
案例:在线购书系统中,要求不修改BookBizImpl代码的情况下增加如下功能:对买书的用户进行返利:每买本书返利3元。(后置通知)
这里需要加入一个适配器
也就是需要在spring-context.xml 里加入

<!-- 过滤通知 -->
	<bean id="MyRegexpMethodPointcutAdvisor" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
		<!-- 设置规则 -->
		<property name="advice" ref="myAfterReturningAdvice"></property>
		<!-- <property name="pattern" value=".*buy"></property> -->
		<!-- 多种条件 -->
		<property name="patterns">
			<list>
				<value>.*buy</value>
			</list>
		</property>
	</bean>
public class MyAfterReturningAdvice implements AfterReturningAdvice {

	@Override
	public void afterReturning(Object arg0, Method arg1, Object[] arg2, Object arg3) throws Throwable {
		String clzName = arg3.getClass().getName();
		String methodName = arg1.getName();
		String params = Arrays.toString(arg2);
		System.out.println("【后置通知(买书返利)】:"+clzName+"."+methodName+"("+params+")");


	}

}

环绕通知

(org.aopalliance.intercept.MethodInterceptor):包围一个连接点的通知,最大特点是可以修改返回值,由于它在方法前后都加入了自己的逻辑代码,因此功能异常强大。它通过MethodInvocation.proceed()来调用目标方法(甚至可以不调用,这样目标方法就不会执行)
案例:修改日志系统不光要输出参数,还要输出返回值(环绕通知)

public class MyMethodInterceptor implements MethodInterceptor {

	@Override
	public Object invoke(MethodInvocation arg0) throws Throwable {

		String clzName = arg0.getThis().getClass().getName();
		String methodName = arg0.getMethod().getName();
		String params = Arrays.toString(arg0.getArguments());
		System.out.println("【环绕通知】:"+clzName+"."+methodName+"("+params+")");
//		returnValue 是代理对象调用目标对象方法的返回值
		Object returnValue = arg0.proceed();
		System.out.println("【环绕通知】:"+clzName+"."+methodName+"("+params+")"+" 方法调用的返回值"+returnValue);
//		
		
		return returnValue;
	}

}

这个接口里面没有定义方法,我们要求我们的类必须实现afterThrows这个方法
public void afterThrowing( [Method method,] [Object args,] [Object target,] Throwable throwable );
前面三个参数都是可选的,只有第三个参数是必须的,同时我们还可以在同一个类中定义这个方法的多个版本,如:
public void afterThrowing( MyException1 ex ) {}
public void afterThrowing( MyException2 ex ) {}
具体那个方法被调用则根据具体的Exception来判断,由AOP容器自动识别 执行

异常通知

org.springframework.aop.ThrowsAdvice
出现异常执行系统提示,然后进行处理。

public class MyThrowsAdvice implements ThrowsAdvice {
	public void afterThrowing( PriceException ex ) {
		System.out.println("价格输入有误,购买失败,请重新输入!!!");
		//下面写入回滚的代码
	}
}

测试代码

public class Demo1 {
	public static void main(String[] args) {
		ApplicationContext context =new ClassPathXmlApplicationContext("spring-context.xml");
//		调用代理对象
		IBookBiz bean = (IBookBiz)context.getBean("bookBizProxy");
//		IBookBiz bean = (IBookBiz)context.getBean("bookBiz");

		bean.buy("李庆喜", "圣墟", 88d);
		//评论
		bean.comment("李庆喜", "虚了");
	}

}

异常结果:
出现这是真正确的,出现这个是报错是没有处理这个代码。。。。。
在这里插入图片描述
全部测试:
这里买书返利只出现了一次,说明购买成功后可以返利了,哈哈哈哈
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值