Spring AOP思想

1 . AOP

       AOP(Aspect Oriented Programming)称为面向切面编程,它利用一种称为"横切"的技术,剖解开封装的对象内部,并将那些影响了多个类的公共行为封装到一个可重用模块,并将其命名为"Aspect",即切面。所谓"切面",简单说就是那些与业务无关,却为业务模块所共同调用的逻辑或责任封装起来,便于减少系统的重复代码,降低模块之间的耦合度,并有利于未来的可操作性和可维护性。在程序开发中主要用来解决一些系统层面上的问题,比如日志,事务,权限等等

 

2 . AOP中关键性概念 

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

       2.2 目标(Target):被通知(被代理)的对象

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

       2.4 代理(Proxy):将通知应用到目标对象后创建的对象(代理=目标+通知),请注意:只有代理对象才有AOP功能,而AOP的代码是写在通知的方法里面的

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

 

3 . AOP带来的好处 (实现 aop 通知接口)

For example (举个栗子)  : 买书,评论

IBookBiz.java

package com.practice.aop.biz;

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

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

BookBizImpl.java

package com.practice.aop.biz.impl;

import com.practice.aop.biz.IBookBiz;
import com.practice.aop.exception.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 + "RMB");
		return true;
	}

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

}

PriceException.java

package com.practice.aop.exception;

public class PriceException extends RuntimeException {

	private static final long serialVersionUID = 3153726424537744253L;

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

测试类.java

package com.practice.ioc.test;

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

import com.practice.aop.biz.IBookBiz;

/**
 * 测试
 * @author Administrator
 *
 */
public class AopTest {

	@SuppressWarnings("resource")
	public static void main(String[] args) {
		// 通过对spring-context.xml进行建模,获取spring上下文
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-context.xml");
		// 获取JavaBean实体,通过文件配置的ID获取
		Object bean = applicationContext.getBean("bookProxy");
//		System.out.println(bean.getClass().getName());
		
		IBookBiz bb = (IBookBiz) bean;
		bb.buy("三叶", "恒", 67d);
		bb.comment("龙", "么");
	}

}

 

       3.1 前置通知
             实现org.springframework.aop.MethodBeforeAdvice接口
             example(栗子) :买书、评论前加系统日志

package com.practice.aop.advice;

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

import org.springframework.aop.MethodBeforeAdvice;

/**
 * 前置通知
 * 方法程序设置通知
 * @author Administrator
 *
 */
public class MyMethodBeforeAdvice implements MethodBeforeAdvice{

	/**
	 * 前置通知执行
	 */
	@Override
	public void before(Method method, Object[] args, Object target) throws Throwable {
		//获取目标名(被通知对象)
		String targetName = target.getClass().getName();
		//目标通知方法
		String methodName = method.getName();
		//方法参数
		String params = Arrays.toString(args);
		System.out.println("前置通知日志:" + targetName + "的目标方法" + methodName + "被调用,携带了参数" + params);
	}
	
}

       3.2 后置通知
             实现org.springframework.aop.AfterReturningAdvice接口
             example(栗子) :买书返利(存在bug)

package com.practice.aop.advice;

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

import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice;

/**
 * 后置通知
 * 方法程序设置通知
 * @author Administrator
 *
 */
public class MyAfterReturnAdvice implements AfterReturningAdvice{

	/**
	 * 后置通知执行
	 */
	public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
		//获取目标名(被通知对象)
		String targetName = target.getClass().getName();
		//目标通知方法
		String methodName = method.getName();
		//方法参数
		String params = Arrays.toString(args);
		System.out.println("后置通知日志:" + targetName + "的目标方法" + methodName + "被调用,携带了参数" + params + "返回了" + returnValue);
	}
	
}

       3.3 环绕通知
             实现 org.aopalliance.intercept.MethodInterceptor 接口
             example(栗子) :类似拦截器,会包括切入点,目标类前后都会执行代码。(环绕执行)

package com.practice.aop.advice;

import java.util.Arrays;

import org.aopalliance.intercept.MethodInvocation;

/**
 * 环绕通知
 * 方法程序设置通知
 * @author Administrator
 *
 */
public class MyMehtodInterceptorAdvice implements org.aopalliance.intercept.MethodInterceptor{

	/**
	 * 环绕通知执行
	 */
	@Override
	public Object invoke(MethodInvocation invocation) throws Throwable {
		//获取目标名(被通知对象)  获取当前接入点再通过反射实例化,获取到目标对象
		String targetName = invocation.getThis().getClass().getName();
		//目标通知方法
		String methodName = invocation.getMethod().getName();
		//方法参数
		String params = Arrays.toString(invocation.getArguments());
		System.out.println("环绕通知日志:" + targetName + "的目标方法" + methodName + "被调用,携带了参数" + params);
		Object returnValue = invocation.proceed();//proceed  作名词:获利,收入
		System.out.println("返回了" + returnValue);
		return returnValue;	
	}
	
}

       3.4 异常通知
             实现 org.springframework.aop.ThrowsAdvice 接口
             example(栗子) :出现异常执行系统提示,然后进行处理。价格异常为例

package com.practice.aop.advice;

import org.springframework.aop.ThrowsAdvice;

import com.practice.aop.exception.PriceException;

/**
 * 异常通知
 * 方法程序设置通知
 * @author Administrator
 *
 */
public class MyThrowAdvice implements ThrowsAdvice{

	/**
	 * 异常通知执行
	 */
	public void afterThrowing( PriceException ex ) {
		System.out.println("异常通知!!" + ex);
	}
}

注 : 这个接口里面没有定义方法,我们要求我们的类必须实现afterThrows这个方法, 必须取 afterThrows 为方法名

       3.5 过滤通知(适配器)
             实现 org.springframework.aop.support.RegexpMethodPointcutAdvisor 接口 ( 直接在spring配置文件进行bean的配置 )
             example(栗子) :处理买书返利的bug

注 : 在使用过滤通知时,需先关闭后置通知的使用

spring-context.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"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
	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-4.3.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
	<!-- 目标对象 -->
	<bean class="com.practice.aop.biz.impl.BookBizImpl" name="bookTarget"></bean>
	<!-- 前置通知对象 -->
	<bean class="com.practice.aop.advice.MyMethodBeforeAdvice" name="myMethodBeforeAdvice"></bean>
	<!-- 后置通知对象 -->
	<bean class="com.practice.aop.advice.MyAfterReturnAdvice" name="myAfterReturnAdvice"></bean>
	<!-- 环绕通知对象 -->
	<bean class="com.practice.aop.advice.MyMehtodInterceptorAdvice" name="myMehtodInterceptorAdvice"></bean>
	<!-- 异常通知对象 -->
	<bean class="com.practice.aop.advice.MyThrowAdvice" name="myThrowAdvice"></bean>
	<!-- 过滤通知对象 --><!-- RegexpMethodPointcutAdvisor正则表达式过滤该切入点方法     advisor劝告者 -->
	<bean class="org.springframework.aop.support.RegexpMethodPointcutAdvisor" name="myRegexpMethodPointcutAdvisor">
		<!-- 具体过滤哪个通知 -->
		<property name="advice" ref="myAfterReturnAdvice"></property>
		<!-- 判断以什么名字结尾的方法目标 -->
		<property name="pattern" value=".*buy"></property>
	</bean>
	<!-- 代理工厂对象   由spring提供 -->
	<bean class="org.springframework.aop.framework.ProxyFactoryBean" name="bookProxy">
		<!-- 代理配置目标 -->
		<property name="target" ref="bookTarget"></property>
		<!-- 代理配置通知     配置类似拦截器 -->
		<property name="interceptorNames">
			<list>
				<value>myMethodBeforeAdvice</value>
<!-- 				<value>myAfterReturnAdvice</value> -->
				<value>myMehtodInterceptorAdvice</value>
				<value>myThrowAdvice</value>
				<value>myRegexpMethodPointcutAdvisor</value>
			</list>
		</property>
		<!-- 代理指定目标对象所实现的接口 -->
		<property name="proxyInterfaces">
			<list>
				<value>com.practice.aop.biz.IBookBiz</value>
			</list>
		</property>
	</bean>
	
</beans>

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值