Spring AOP

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

目标(Target):被通知(被代理)的对象
注1:完成具体的业务逻辑
通知(Advice):在某个特定的连接点上执行的动作,同时Advice也是程序代码的具体实现,例如一个实现日志记录的代码(通知有些书上也称为处理)
注2:完成切面编程
代理(Proxy):将通知应用到目标对象后创建的对象(代理=目标+通知),
例子:外科医生+护士
注3:只有代理对象才有AOP功能,而AOP的代码是写在通知的方法里面的
切入点(Pointcut):多个连接点的集合,定义了通知应该应用到那些连接点。
(也将Pointcut理解成一个条件 ,此条件决定了容器在什么情况下将通知和目标组合成代理返回给外部程序)

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

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

AOP:

即面向切面编程

AOP带来的好处:

让我们可以 “专心做事”

案例:
spring-context.xml配置文件:
在这里插入图片描述
在这里插入图片描述

<!-- 目标对象 -->
	<bean class="com.zking.aop.biz.impl.BookBizImpl" id="bookBiz"></bean>
	
	<!-- 前置通知 -->
	<bean class="com.zking.aop.advice.MyMethodBeforeAdvice" id="myMethodBeforeAdvice"></bean>
	
	<!-- 后置通知 -->
	<bean class="com.zking.aop.advice.MyAfterReturningAdvice" id="myAfterReturningAdvice" ></bean>
	
	<!-- 环绕通知 -->
	<bean class="com.zking.aop.advice.MyMethodInterceptor" id="myMethodInterceptor"></bean>
	
	<!-- 异常通知 -->
	<bean class="com.zking.aop.advice.MyThrowsAdvice" id="myThrowsAdvice" ></bean>
	
	<!-- 过滤通知(适配器) -->
	<bean class="org.springframework.aop.support.RegexpMethodPointcutAdvisor" id="myAfterReturningAdvice2" >
		<property name="advice" ref="myAfterReturningAdvice" ></property>
		<!-- .*buy:[.*]任意字符0~n个,已buy结尾的方法 -->
		<property name="pattern" value=".*buy" ></property>
	</bean>
	
	<!-- 生成代理(目标对象+通知) -->
	<bean class="org.springframework.aop.framework.ProxyFactoryBean" id="proxyFactoryBean" >
		<!-- 目标 -->
		<property name="target" ref="bookBiz"></property>
		<!-- 代理工厂生产的代理需要实现的接口列表 -->
		<property name="proxyInterfaces"  >
			<list>
				<value>com.zking.aop.biz.IBookBiz</value>
			</list>
		</property>
		<!-- 通知 -->
		<property name="interceptorNames">
			<list>
				<value>myMethodBeforeAdvice</value>
				<!-- <value>myAfterReturningAdvice</value> -->
				<!-- <value>myAfterReturningAdvice2</value> -->
				<!-- <value>myMethodInterceptor</value> -->
				<!-- <value>myThrowsAdvice</value> -->
			</list>
		</property>

IBookBiz :

package com.zking.aop.biz;

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

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

BookBizImpl :

package com.zking.aop.biz.impl;

import com.zking.aop.biz.IBookBiz;
import com.zking.aop.ex.PriceException;

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);
	}

}

测试类:
在这里插入图片描述

1、前置通知

实现org.springframework.aop.MethodBeforeAdvice接口
例如:买书、评论前加系统日志
在这里插入图片描述

package com.zking.aop.advice;

import java.lang.reflect.Method;
import java.util.Arrays;

import org.springframework.aop.MethodBeforeAdvice;

/**
 * 前置通知:
 * 调用项目中的某一接口实现类的方法时,将类名、方法名,携带的参数,作为日志存储到数据库。
 * @author Administrator
 *
 */
public class MyMethodBeforeAdvice implements MethodBeforeAdvice {

	public void before(Method method, Object[] args, Object target) throws Throwable {
		// TODO Auto-generated method stub
		String targetName = target.getClass().getName();
		String methodName = method.getName();
		String params = Arrays.toString(args);
		String msg = "[系统日志]:正在调用--》"+targetName+"."+methodName+",携带的参数:"+params;
		System.out.println(msg);
		
	}

}

效果:在连接点之前执行的通知()

在这里插入图片描述

2、后置通知

实现org.springframework.aop.AfterReturningAdvice接口
买书返利(存在bug)
在这里插入图片描述

package com.zking.aop.advice;

import java.lang.reflect.Method;
import java.util.Arrays;

import org.springframework.aop.AfterReturningAdvice;

/**
 * 后置通知
 * @author Administrator
 *
 */
public class MyAfterReturningAdvice implements AfterReturningAdvice {

	public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
		// TODO Auto-generated method stub
		String targetName = target.getClass().getName();
		String methodName = method.getName();
		String params = Arrays.toString(args);
		String msg = "[后置通知]:返利   0$   --》"+targetName+"."+methodName+",携带的参数:"+params+",目标对象所调用的方法的返回值"+returnValue;
		System.out.println(msg);
	}

}

效果:在连接点之前执行的通知()

在这里插入图片描述

3、环绕通知

org.aopalliance.intercept.MethodInterceptor
类似过滤器,会包括切入点,目标类前后都会执行代码。

在这里插入图片描述

package com.zking.aop.advice;

import java.lang.reflect.Method;
import java.util.Arrays;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

/**
 * 环绕通知
 * @author Administrator
 *
 */
public class MyMethodInterceptor implements MethodInterceptor {

	public Object invoke(MethodInvocation invocation) throws Throwable {
		
		Object target = invocation.getThis();
		Method method = invocation.getMethod();
		Object[] args = invocation.getArguments();
		
		String targetName = target.getClass().getName();
		String methodName = method.getName();
		String params = Arrays.toString(args);
		String msg = "[环绕通知]:---  --》"+targetName+"."+methodName+",携带的参数:"+params;
		System.out.println(msg);
		
		Object returnValue = invocation.proceed();
		
		String msg2 = "[环绕通知]:---  --》"+targetName+"."+methodName+",携带的参数:"+params+",目标对象所调用的方法的返回值"+returnValue;
		System.out.println(msg2);
		
		return returnValue;
	}

}

效果:包围一个连接点的通知,最大特点是可以修改返回值,由于它在方法前后都加入了自己的逻辑代码,因此功能异常强大。
它通过MethodInvocation.proceed()来调用目标方法(甚至可以不调用,这样目标方法就不会执行)

在这里插入图片描述

4、异常通知

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

异常类:

package com.zking.aop.ex;

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);
	}
	
}

在这里插入图片描述

package com.zking.aop.advice;

import org.springframework.aop.ThrowsAdvice;

import com.zking.aop.ex.PriceException;

public class MyThrowsAdvice implements ThrowsAdvice {

	public void afterThrowing( PriceException ex ) {
		System.out.println("输入的价格有误,购买失败,请重新输入!!!!");		
	}
	
}

效果:这个通知会在方法抛出异常退出时执行

在这里插入图片描述

5、过滤通知(适配器)

org.springframework.aop.support.RegexpMethodPointcutAdvisor
处理买书返利的bug
在这里插入图片描述

效果:
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值