Spring之aop

1.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)
 

一、aop的介绍

1、通过案例介绍aop是什么:

①、过程:

②、需求:记录张三把001数据清除了 

package com.lsy.aop.test;

public class OrderDao {
	public void del() {
		System.out.println("删除数据库中的订单");
		/**
		 * 需求:记录张三把001这条数据清除了
		 * 1.日志表
		 * 2.增删改查的功能
		 * 3.LogDao.insert();
		 */
	}
}
package com.lsy.aop.test;

public class BookDao {
	public void del() {
		//用户得登录
		System.out.println("删除数据库中的书籍");
		/**
		 * 需求:记录张三把001这条数据清除了
		 LogDao.insert();
		 */
	}
}

2、前置通知

①、导入需要使用相关类

(1)异常类

package com.lsy.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)接口

package com.lsy.aop.biz;

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

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

(3)实现类

package com.lsy.aop.biz.impl;

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

}

②、测试类

package com.lsy.aop.test;

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

import com.lsy.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("李四","西游记", 36.0d);
		bookbiz.comment("李四", "猴哥等等我");
	}
}

(1)配置:

<!-- 目标 -->
    <bean name="bookBiz" class="com.lsy.aop.biz.impl.BookBizImpl "></bean>

③、前置通知

target:目标对象
method:被触发的目标对象的方法
args:目标对象的目标方法的携带的参数

package com.lsy.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 targetName = target.getClass().getName();
		String methodName = method.getName();
		String params = Arrays.toString(args);
		String msg = "【系统日志】:正在调用->"+targetName+"."+methodName+",携带的参数:"+params;
		System.out.println(msg);

	}

}

(1)配置:

<?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.lsy.ioc.biz.impl.UserBizImpl1"></bean> -->
<bean name="userBiz1" class="com.lsy.ioc.biz.impl.UserBizImpl1"></bean>
<bean name="userBiz2" class="com.lsy.ioc.biz.impl.UserBizImpl2"></bean>
<bean name="personAction" class="com.lsy.ioc.web.PersonAction">
	<property name="userBiz" ref="userBiz2"></property>
</bean>
<bean name="userAction" class="com.lsy.ioc.web.UserAction">
	<property name="userBiz" ref="userBiz1"></property>
	</bean>
	<bean name="userAction2" class="com.lsy.ioc.web.UserAction2">
	<property name="userBiz" ref="userBiz1"></property>
	</bean>
	<bean name="userAction3" class="com.lsy.ioc.web.UserAction3">
	<property name="userBiz" ref="userBiz1"></property>
	</bean>
	
	<bean name="paramAction" class="com.lsy.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="19"></constructor-arg>
	<constructor-arg name="hobby">
	<list>
	<value>吃喝</value>
	<value>玩乐</value>
	</list>
	
	</constructor-arg>
	</bean>
	<!-- 目标 -->
	<bean name="bookBiz" class="com.lsy.aop.biz.impl.BookBizImpl "></bean>
	<!-- 前置通知 -->
	<bean name="myBefore" class="com.lsy.aop.advice.MyMethodBeforeAdvice"></bean>
	
	<!-- 生成代理对象(目标+通知) -->
	<bean class="org.springframework.aop.framework.ProxyFactoryBean"
		id="proxyFactoryBean">
		<!-- 目标对象 -->
		<property name="target" ref="bookBiz"></property>
		<!-- 代理工厂生产的代理需要实现的接口列表 -->
		<property name="proxyInterfaces">
			<list>
				<value>com.lsy.aop.biz.IBookBiz</value>
			</list>
		</property>
		<property name="interceptorNames">
			<list>
				<value>myBefore</value>
			</list>
		</property>
	</bean>
	
	
	
</beans>

(2)测试及结果:

 3、后置通知

后置通知一般在方法的结尾,比前置通知多一个属性,因为方法结束后还会有一个返回值;

returnValue:返回值

package com.lsy.aop.advice;

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

import org.springframework.aop.AfterReturningAdvice;

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

}

①、配置:

<?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.lsy.ioc.biz.impl.UserBizImpl1"></bean> -->
<bean name="userBiz1" class="com.lsy.ioc.biz.impl.UserBizImpl1"></bean>
<bean name="userBiz2" class="com.lsy.ioc.biz.impl.UserBizImpl2"></bean>
<bean name="personAction" class="com.lsy.ioc.web.PersonAction">
	<property name="userBiz" ref="userBiz2"></property>
</bean>
<bean name="userAction" class="com.lsy.ioc.web.UserAction">
	<property name="userBiz" ref="userBiz1"></property>
	</bean>
	<bean name="userAction2" class="com.lsy.ioc.web.UserAction2">
	<property name="userBiz" ref="userBiz1"></property>
	</bean>
	<bean name="userAction3" class="com.lsy.ioc.web.UserAction3">
	<property name="userBiz" ref="userBiz1"></property>
	</bean>
	
	<bean name="paramAction" class="com.lsy.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="19"></constructor-arg>
	<constructor-arg name="hobby">
	<list>
	<value>吃喝</value>
	<value>玩乐</value>
	</list>
	
	</constructor-arg>
	</bean>
	<!-- 目标 -->
	<bean name="bookBiz" class="com.lsy.aop.biz.impl.BookBizImpl "></bean>
	<!-- 前置通知 -->
	<bean name="myBefore" class="com.lsy.aop.advice.MyMethodBeforeAdvice"></bean>
	
	<!-- 生成代理对象(目标+通知) -->
	<bean class="org.springframework.aop.framework.ProxyFactoryBean"
		id="proxyFactoryBean">
		<!-- 目标对象 -->
		<property name="target" ref="bookBiz"></property>
		<!-- 代理工厂生产的代理需要实现的接口列表 -->
		<property name="proxyInterfaces">
			<list>
				<value>com.lsy.aop.biz.IBookBiz</value>
			</list>
		</property>
		<property name="interceptorNames">
			<list>
				<value>myBefore</value>
                <value>myAfter</value>
			</list>
		</property>
	</bean>
	
	
	
</beans>

4、环绕通知

//invocation可以执行被代理的目标对象的业务方法    (相当于过滤器    chain.dofilter:放行)
        Object returnValue = invocation.proceed();

package com.lsy.aop.advice;

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

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

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

}

①、配置:

<?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.lsy.ioc.biz.impl.UserBizImpl1"></bean> -->
<bean name="userBiz1" class="com.lsy.ioc.biz.impl.UserBizImpl1"></bean>
<bean name="userBiz2" class="com.lsy.ioc.biz.impl.UserBizImpl2"></bean>
<bean name="personAction" class="com.lsy.ioc.web.PersonAction">
	<property name="userBiz" ref="userBiz2"></property>
</bean>
<bean name="userAction" class="com.lsy.ioc.web.UserAction">
	<property name="userBiz" ref="userBiz1"></property>
	</bean>
	<bean name="userAction2" class="com.lsy.ioc.web.UserAction2">
	<property name="userBiz" ref="userBiz1"></property>
	</bean>
	<bean name="userAction3" class="com.lsy.ioc.web.UserAction3">
	<property name="userBiz" ref="userBiz1"></property>
	</bean>
	
	<bean name="paramAction" class="com.lsy.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="19"></constructor-arg>
	<constructor-arg name="hobby">
	<list>
	<value>吃喝</value>
	<value>玩乐</value>
	</list>
	
	</constructor-arg>
	</bean>
	<!-- 目标 -->
	<bean name="bookBiz" class="com.lsy.aop.biz.impl.BookBizImpl "></bean>
	<!-- 前置通知 -->
	<bean name="myBefore" class="com.lsy.aop.advice.MyMethodBeforeAdvice"></bean>
	
	<!-- 生成代理对象(目标+通知) -->
	<bean class="org.springframework.aop.framework.ProxyFactoryBean"
		id="proxyFactoryBean">
		<!-- 目标对象 -->
		<property name="target" ref="bookBiz"></property>
		<!-- 代理工厂生产的代理需要实现的接口列表 -->
		<property name="proxyInterfaces">
			<list>
				<value>com.lsy.aop.biz.IBookBiz</value>
			</list>
		</property>
		<property name="interceptorNames">
			<list>
				<value>myBefore</value>
                <value>myAfter</value>
                <value>myMethod</value>    
			</list>
		</property>
	</bean>
	
	
	
</beans>

②、测试及结果

 

5、异常通知

例如:加入订单插入失败,订单项肯定是不能插入的(要么同时成功,要么同时失败)

所以说一下就是处理失败的业务逻辑代码,可以将数据进行回滚;

异常通知可以没有实现方法,但是别的都有实现方法,方法名不能修改

package com.lsy.aop.advice;

import org.springframework.aop.ThrowsAdvice;

import com.lsy.aop.exception.PriceException;

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

①、配置:

<?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.lsy.ioc.biz.impl.UserBizImpl1"></bean> -->
<bean name="userBiz1" class="com.lsy.ioc.biz.impl.UserBizImpl1"></bean>
<bean name="userBiz2" class="com.lsy.ioc.biz.impl.UserBizImpl2"></bean>
<bean name="personAction" class="com.lsy.ioc.web.PersonAction">
	<property name="userBiz" ref="userBiz2"></property>
</bean>
<bean name="userAction" class="com.lsy.ioc.web.UserAction">
	<property name="userBiz" ref="userBiz1"></property>
	</bean>
	<bean name="userAction2" class="com.lsy.ioc.web.UserAction2">
	<property name="userBiz" ref="userBiz1"></property>
	</bean>
	<bean name="userAction3" class="com.lsy.ioc.web.UserAction3">
	<property name="userBiz" ref="userBiz1"></property>
	</bean>
	
	<bean name="paramAction" class="com.lsy.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="19"></constructor-arg>
	<constructor-arg name="hobby">
	<list>
	<value>吃喝</value>
	<value>玩乐</value>
	</list>
	
	</constructor-arg>
	</bean>
	<!-- 目标 -->
	<bean name="bookBiz" class="com.lsy.aop.biz.impl.BookBizImpl "></bean>
	<!-- 前置通知 -->
	<bean name="myBefore" class="com.lsy.aop.advice.MyMethodBeforeAdvice"></bean>
	
	<!-- 生成代理对象(目标+通知) -->
	<bean class="org.springframework.aop.framework.ProxyFactoryBean"
		id="proxyFactoryBean">
		<!-- 目标对象 -->
		<property name="target" ref="bookBiz"></property>
		<!-- 代理工厂生产的代理需要实现的接口列表 -->
		<property name="proxyInterfaces">
			<list>
				<value>com.lsy.aop.biz.IBookBiz</value>
			</list>
		</property>
		<property name="interceptorNames">
			<list>
				<value>myBefore</value>
                <value>myAfter</value>
                <value>myMethod</value>
                <value>myThrows</value>    
			</list>
		</property>
	</bean>
	
	
	
</beans>

②、测试及结果

将价格改为负数,看异常

6、过滤通知

①、配置

org.springframework.aop.support.RegexpMethodPointcutAdvisor   这个类是固定的   myAfter2:过滤的是后置通知 

 

<!-- 过滤通知 -->
	<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">
		<!-- 目标对象 -->
		<property name="target" ref="bookBiz"></property>
		<!-- 代理工厂生产的代理需要实现的接口列表 -->
		<property name="proxyInterfaces">
			<list>
				<value>com.lsy.aop.biz.IBookBiz</value>
			</list>
		</property>
		<property name="interceptorNames">
			<list>
				<value>myBefore</value>
				<!-- <value>myAfter</value> -->
				<value>myAfter2</value>
				<value>myMethod</value>
				<value>myThrows</value>
			</list>
		</property>
	</bean>
	

②、测试及结果

只有买书有返利,评论没有返利;

 bye~

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值