spring之aop

一、AOP中关键性概念 :

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

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

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

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

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

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

2、如何实现AOP

①、目标对象只负责业务逻辑代码;

②、通知对象负责AOP代码,这二个对象都没有AOP的功能,只有代理对象才有;

3、AOP:即面向切面编程

4、 AOP带来的好处:让我们可以 “专心做事”

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

6、 前置通知(org.springframework.aop.MethodBeforeAdvice):在连接点之前执行的通知()

7、后置通知(org.springframework.aop.AfterReturningAdvice):在连接点正常完成后执行的通知

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

9、异常通知(org.springframework.aop.ThrowsAdvice):这个通知会在方法抛出异常退出时执行

10、适配器(org.springframework.aop.support.RegexpMethodPointcutAdvisor) 适配器=通知                  (Advice)+切入点(Pointcut)

二、导入需要使用相关类

1、异常类

PriceException:

package com.ysq.aop.exception;

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

2、接口类

IBookBiz:

package com.ysq.aop.biz;

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

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

3、IBookBiz的实现类

BookBizImpl:

package com.ysq.aop.biz.impl;

import com.ysq.aop.biz.IBookBiz;
import com.ysq.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);
		return true;
	}

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

}

4、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: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/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
	<!-- 本文件中配置整个项目中包含的所有javabean,目的在于spring统一关联 -->
	<bean name="userBiz1" class="com.ysq.ioc.biz.impl.UserBizImpl1"></bean>
	<bean name="userBiz2" class="com.ysq.ioc.biz.impl.UserBizImpl2"></bean>
	<bean name="personAction" class="com.ysq.ioc.web.PersonAction">
		<property name="userBiz" ref="userBiz1"></property>
	</bean>
	<bean name="userAction" class="com.ysq.ioc.web.UserAction">
	</bean>
	<bean name="paramAction" class="com.ysq.ioc.web.ParamAction">
		<!-- <property name="name" value="小白"></property> <property name="age" 
			value="18"></property> <property name="hobby"> <list> <value>帅哥</value> <value>帅哥</value> 
			<value>帅哥</value> </list> </property> -->
		<constructor-arg name="name" value="周颖"></constructor-arg>
		<constructor-arg name="age" value="38"></constructor-arg>
		<constructor-arg name="hobby">
			<list>
				<value>拉屎</value>
				<value>吃饭</value>
				<value>睡觉</value>
			</list>
		</constructor-arg>
	</bean>
	<!-- 目标 -->
	<bean name="bookBiz" class="com.ysq.aop.biz.impl.BookBizImpl"></bean>
	<!-- 前置通知 -->
	<bean name="myBefore" class="com.ysq.aop.advice.MyMethodBeforeAdvice"></bean>
	<!-- 后置通知 -->
	<bean name="myAfter" class="com.ysq.aop.advice.MyAfterReturningAdvice"></bean>
	<!-- 环绕通知 -->
	<bean name="myFilterAdvice" class="com.ysq.aop.advice.MyMethodInterceptor"></bean>
	<!-- 异常通知 -->
	<bean name="myExceptionAdvice" class="com.ysq.aop.advice.MyThrowsAdvice"></bean>
	<!--过滤通知  -->
<bean class="org.springframework.aop.support.RegexpMethodPointcutAdvisor"
		id="myAfter2">
		<property name="advice" ref="myAfter"></property>
		<!-- .*buy:[.*]任意字符0~n个,以buy结尾的方法 -->
		<!-- <property name="pattern" value=".*buy"></property> -->
		<property name="patterns">
			<list>
				<value>.*buy</value>
			</list>
		</property>
	</bean>
	<!--生成代理对象 (目标+通知) -->
	<bean class="org.springframework.aop.framework.ProxyFactoryBean"
		id="proxyFactoryBean">
		<!--ref 目标对象 -->
		<property name="target" ref="bookBiz"></property>
		<!-- 代理工厂生产的代理需要实现的接口列表 -->
		<property name="proxyInterfaces">
			<list>
				<value>com.ysq.aop.biz.IBookBiz</value>
			</list>
		</property>
		<!--绑定的那些通知 -->
		<property name="interceptorNames">
			<list>
				<value>myBefore</value>
				<!-- <value>myAfter</value> -->
				<value>myAfter2</value>
				 <value>myFilterAdvice</value>
				 <value>myExceptionAdvice</value>
				
			</list>
		</property>
	</bean>
</beans>

5、 测试类AopTest.java

package com.ysq.aop.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.ysq.aop.biz.IBookBiz;

public class AopTest {
	public static void main(String[] args) {
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/spring-context.xml");
		IBookBiz bookBiz = (IBookBiz) applicationContext.getBean("proxyFactoryBean");
		bookBiz.buy("小白", "陈情令", 19.9d);
		bookBiz.comment("小白", "魏无羡太帅了");
	}
	
}

三、前置通知

前置通知的价值在于:创建session,开启事务

1、MyMethodBeforeAdvice (要实现MethodBeforeAdvice接口):

package com.ysq.aop.advice;
import java.lang.reflect.Method;
import java.util.Arrays;

import org.springframework.aop.MethodBeforeAdvice;

/**
 * 前置通知
 * @author zjjt
 *
 */
public class MyMethodBeforeAdvice implements MethodBeforeAdvice {

	/**
	 * target:目标对象
	 * method:被触发的目标对象的方法
	 * args:目标对象的目标方法的携带参数
	 */
	public void before(Method method, Object[] args, Object target) throws Throwable {
		String clzName = target.getClass().getName();
		String methodName = method.getName();
		String params = Arrays.toString(args);
		System.out.println("【买书、评论前加系统日志】:"+clzName + "." + methodName +"("+params+")");
	}

}

2、配置spring-context.xml

	<!-- 前置通知 -->
	<bean name="myBefore" class="com.ysq.aop.advice.MyMethodBeforeAdvice"></bean>
<!--生成代理对象 (目标+通知) -->
	<bean class="org.springframework.aop.framework.ProxyFactoryBean"
		id="proxyFactoryBean">
		<!--ref 目标对象 -->
		<property name="target" ref="bookBiz"></property>
		<!-- 代理工厂生产的代理需要实现的接口列表 -->
		<property name="proxyInterfaces">
			<list>
				<value>com.ysq.aop.biz.IBookBiz</value>
			</list>
		</property>
		<!--绑定的那些通知 -->
		<property name="interceptorNames">
			<list>
				<value>myBefore</value>
			</list>
		</property>
	</bean>

3、测试及运行结果

package com.ysq.aop.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.ysq.aop.biz.IBookBiz;

public class AopTest {
	public static void main(String[] args) {
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/spring-context.xml");
		IBookBiz bookBiz = (IBookBiz) applicationContext.getBean("proxyFactoryBean");
		bookBiz.buy("小白", "陈情令", 19.9d);
		bookBiz.comment("小白", "魏无羡太帅了");
	}
	

}

运行结果:

 四、后置通知

相比于前置多了一个参数,返回值

1、MyAfterReturningAdvice (要实现AfterReturningAdvice接口):

package com.ysq.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 {
		String targetName = target.getClass().getName();
		String methodName = method.getName();
		String params = Arrays.toString(args);
		String msg = "【返利通知:返利3元】:正在调用->" + targetName + "." + methodName + ",携带的参数:" + params + ";目标对象所调用的方法的返回值:"
				+ returnValue;
		System.out.println(msg);
	}
 
}

2、配置spring-context.xml

<!-- 后置通知 -->
	<bean name="myAfter" class="com.ysq.aop.advice.MyAfterReturningAdvice"></bean>
<!--生成代理对象 (目标+通知) -->
	<bean class="org.springframework.aop.framework.ProxyFactoryBean"
		id="proxyFactoryBean">
		<!--ref 目标对象 -->
		<property name="target" ref="bookBiz"></property>
		<!-- 代理工厂生产的代理需要实现的接口列表 -->
		<property name="proxyInterfaces">
			<list>
				<value>com.ysq.aop.biz.IBookBiz</value>
			</list>
		</property>
		<!--绑定的那些通知 -->
		<property name="interceptorNames">
			<list>
				
				<value>myAfter</value>
				
			</list>
		</property>
	</bean>

3、测试及运行结果

package com.ysq.aop.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.ysq.aop.biz.IBookBiz;

public class AopTest {
	public static void main(String[] args) {
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/spring-context.xml");
		IBookBiz bookBiz = (IBookBiz) applicationContext.getBean("proxyFactoryBean");
		bookBiz.buy("小白", "陈情令", 19.9d);
		bookBiz.comment("小白", "魏无羡太帅了");
	}
	

}

运行结果:

 五、环绕通知:包含前置+后置通知

1、环绕通知MythodInterceptor(要实现MethodInterceptor接口):

package com.ysq.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();
		// a.jsp window.open(b.jsp)
		// b.jsp xxx->返回object->b.jsp window.close();window.getArguments;
		String targetName = target.getClass().getName();
		String methodName = method.getName();
		String params = Arrays.toString(args);
		String msg = "【环绕通知】:正在调用->" + targetName + "." + methodName + ",携带的参数:" + params;
		System.out.println(msg);
		//invocation可以执行被代理的目标对象的业务方法
		Object returnValue = invocation.proceed();
		String msg2 = "【环绕通知】:目标对象所调用的方法的返回值:" + returnValue;
		System.out.println(msg2);
		return returnValue;
	}

}

2、配置spring-context.xml

<!-- 环绕通知 -->
	<bean name="myFilterAdvice" class="com.ysq.aop.advice.MyMethodInterceptor"></bean>
<!--生成代理对象 (目标+通知) -->
	<bean class="org.springframework.aop.framework.ProxyFactoryBean"
		id="proxyFactoryBean">
		<!--ref 目标对象 -->
		<property name="target" ref="bookBiz"></property>
		<!-- 代理工厂生产的代理需要实现的接口列表 -->
		<property name="proxyInterfaces">
			<list>
				<value>com.ysq.aop.biz.IBookBiz</value>
			</list>
		</property>
		<!--绑定的那些通知 -->
		<property name="interceptorNames">
			<list>
				 <value>myFilterAdvice</value>
				 
			</list>
		</property>
	</bean>

3、测试及运行结果:

package com.ysq.aop.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.ysq.aop.biz.IBookBiz;

public class AopTest {
	public static void main(String[] args) {
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/spring-context.xml");
		IBookBiz bookBiz = (IBookBiz) applicationContext.getBean("proxyFactoryBean");
		bookBiz.buy("小白", "陈情令", 19.9d);
		bookBiz.comment("小白", "魏无羡太帅了");
	}
	

}

运行结果: 

六、异常通知

1、MyThrowsAdvice(要实现ThrowsAdvice接口):

package com.ysq.aop.advice;
import org.springframework.aop.ThrowsAdvice;

import com.ysq.aop.exception.PriceException;


/**
 * 异常通知
 * @author Administrator
 *
 */
public class MyThrowsAdvice implements ThrowsAdvice {
	public void afterThrowing( PriceException ex ) {
		System.out.println("价格输入有误,购买失败,请重新输入!!!");
	}
}

2、配置spring-context.xml

<!-- 异常通知 -->
	<bean name="myExceptionAdvice" class="com.ysq.aop.advice.MyThrowsAdvice"></bean>
<!--生成代理对象 (目标+通知) -->
	<bean class="org.springframework.aop.framework.ProxyFactoryBean"
		id="proxyFactoryBean">
		<!--ref 目标对象 -->
		<property name="target" ref="bookBiz"></property>
		<!-- 代理工厂生产的代理需要实现的接口列表 -->
		<property name="proxyInterfaces">
			<list>
				<value>com.ysq.aop.biz.IBookBiz</value>
			</list>
		</property>
		<!--绑定的那些通知 -->
		<property name="interceptorNames">
			<list>
				 <value>myExceptionAdvice</value>
				
			</list>
		</property>
	</bean>

3、测试及运行结果

package com.ysq.aop.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.ysq.aop.biz.IBookBiz;

public class AopTest {
	public static void main(String[] args) {
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/spring-context.xml");
		IBookBiz bookBiz = (IBookBiz) applicationContext.getBean("proxyFactoryBean");
		bookBiz.buy("小白", "陈情令", -19.9d);
		bookBiz.comment("小白", "魏无羡太帅了");
	}
	

}

运行结果:

六、过滤通知 

过滤通知:并不是每个方法都需要通知,所有需要过滤一下

配置spring-context.xml(过滤通知替代后置通知) 

<!--过滤通知  -->
<bean class="org.springframework.aop.support.RegexpMethodPointcutAdvisor"
		id="myAfter2">
		<property name="advice" ref="myAfter"></property>
		<!-- .*buy:[.*]任意字符0~n个,以buy结尾的方法 -->
		<!-- <property name="pattern" value=".*buy"></property> -->
		<property name="patterns">
			<list>
				<value>.*buy</value>
			</list>
		</property>
	</bean>
	<!--生成代理对象 (目标+通知) -->
	<bean class="org.springframework.aop.framework.ProxyFactoryBean"
		id="proxyFactoryBean">
		<!--ref 目标对象 -->
		<property name="target" ref="bookBiz"></property>
		<!-- 代理工厂生产的代理需要实现的接口列表 -->
		<property name="proxyInterfaces">
			<list>
				<value>com.ysq.aop.biz.IBookBiz</value>
			</list>
		</property>
		<!--绑定的那些通知 -->
		<property name="interceptorNames">
			<list>
			
				<!-- <value>myAfter</value> -->
				<value>myAfter2</value>
				
			</list>
		</property>
	</bean>

运行结果:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值