spring之AOP

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

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

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

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

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

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

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

1. AOP
即面向切面编程

2. AOP带来的好处
让我们可以 “专心做事”
案例:
public void doSameBusiness (long lParam,String sParam){
// 记录日志
log.info(“调用 doSameBusiness方法,参数是:”+lParam);
// 输入合法性验证
if (lParam<=0){
throws new IllegalArgumentException(“xx应该大于0”);
}
if (sParam==null || sParam.trim().equals("")){
throws new IllegalArgumentException(“xx不能为空”);
}
// 异常处理
try{ …
}catch(…){
}catch(…){
}
// 事务控制
tx.commit();
}

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

4. 前置通知(org.springframework.aop.MethodBeforeAdvice):在连接点之前执行的通知()
案例:在购书系统当中使用AOP方式实现日志系统

5. 后置通知(org.springframework.aop.AfterReturningAdvice):在连接点正常完成后执行的通知
案例:在线购书系统中,要求不修改BookBizImpl代码的情况下增加如下功能:对买书的用户进行返利:每买本书返利3元。(后置通知)
即:每调用一次buy方法打印:“[销售返利][时间]返利3元。”

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

7. 异常通知(org.springframework.aop.ThrowsAdvice):这个通知会在方法抛出异常退出时执行
案例: 书本价格为负数时抛出一个异常,通过异常通知取消此订单

8. 适配器(org.springframework.aop.support.RegexpMethodPointcutAdvisor) 适配器=通知(Advice)+切入点(Pointcut)
案例:通过适配器解决发书评时也返利的问题
.*buy
实例:
BookBizImpl

package com.houyitao.aop.biz.impl;

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

}

IBookBiz

package com.houyitao.aop.biz.impl;

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

}

PriceException

package com.houyitao.aop.biz.impl;

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

}

前置通知
实现org.springframework.aop.MethodBeforeAdvice接口
买书、评论前加系统日志

package com.houyitao.aop.advice;

import java.lang.reflect.Method;
import java.util.Arrays;
/**
 * 前置通知
      实现org.springframework.aop.MethodBeforeAdvice接口
       买书、评论前加系统日志
 * @author hou
 *
 */
public class MethodBeforeAdvice implements org.springframework.aop.MethodBeforeAdvice {

	@Override
	public void before(Method method, Object[] args, Object target) throws Throwable {
		// TODO Auto-generated method stub
		String clzName=target.getClass().getName();
		String methodName=method.getName();
		String params=Arrays.toString(args);
		System.out.println("[买书、评论前加系统日志]:"+clzName+"."+methodName+"("+params+")");
	}


}

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

package com.houyitao.aop.advice;

import java.lang.reflect.Method;
import java.util.Arrays;
/**
 * 后置通知
		实现org.springframework.aop.AfterReturningAdvice接口
		买书返利(存在bug)
 * @author hou
 *
 */
public class AfterReturningAdvice implements org.springframework.aop.AfterReturningAdvice {

	@Override
	public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
		// TODO Auto-generated method stub
		String clzName=target.getClass().getName();
		String methodName=method.getName();
		String params=Arrays.toString(args);
		System.out.println("[买书返利通知]:"+clzName+"."+methodName+"("+params+")"+"\t\t目标对象方法调用后的返回值"+returnValue);
	
	}

}

环绕通知
org.aopalliance.intercept.MethodInterceptor
类似拦截器,会包括切入点,目标类前后都会执行代码。

package com.houyitao.aop.advice;

import java.util.Arrays;

import org.aopalliance.intercept.MethodInvocation;
/**
 * 环绕通知
		org.aopalliance.intercept.MethodInterceptor
		类似拦截器,会包括切入点,目标类前后都会执行代码。
 * @author hou
 *
 */
public class MethodInterceptor implements org.aopalliance.intercept.MethodInterceptor {

	@Override
	public Object invoke(MethodInvocation invocation) throws Throwable {
		// TODO Auto-generated method stub
		String clzName=invocation.getThis().getClass().getName();
		String methodName=invocation.getMethod().getName();
		String params=Arrays.toString(invocation.getArguments());
		
		System.out.println("[环绕通知]:"+clzName+"."+methodName+"("+params+")");
		Object returnValue = invocation.proceed();
		System.out.println("[环绕通知:]"+"\t目标对象方法调用后的返回值"+returnValue);
	
		return returnValue;
	}

}

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

package com.houyitao.aop.advice;

import com.houyitao.aop.ex.PriceException;

/**
 * 异常通知
		org.springframework.aop.ThrowsAdvice
		出现异常执行系统提示,然后进行处理。价格异常为例
 * @author hou
 *
 */
public class ThrowsAdvice implements org.springframework.aop.ThrowsAdvice {
public void afterThrowing(PriceException ex) {
	System.out.println("价格错误");
}
}

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" default-autowire="byName"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">


	<bean class="com.houyitao.ioc.biz.impl.UserBizImpl2" id="userBiz"></bean>
	<bean class="com.houyitao.ioc.web.UserAction" id="xxx">
		<!-- set注入用propert标签 -->
		<!-- <property name="userBiz" ref="userBiz"></property> -->
		<!-- <property name="uname" value="tugou"></property> <property name="age" 
			value="18"></property> -->

		<!-- 构造注入用constructor-arg标签 -->
		<constructor-arg name="uname" value="tugou"></constructor-arg>
		<constructor-arg name="age" value="18"></constructor-arg>
		<property name="hobby">
			<list>
				<value>唱</value>
				<value>rap</value>
				<value>篮球</value>
			</list>
		</property>
	</bean>
	<bean class="com.houyitao.ioc.web.OrderAction" id="ttt">
		<!-- <property name="userBiz" ref="userBiz"></property> -->
	</bean>


	<!-- *****************************************aop************************************** -->
	<!-- 目标对象 -->
	<bean id="bookBiz" class="com.houyitao.aop.biz.impl.BookBizImpl"></bean>
	<!-- 前置通知 -->
	<bean id="myBefore" class="com.houyitao.aop.advice.MethodBeforeAdvice"></bean>
	<!-- 通知 -->
	<bean id="myAfter" class="com.houyitao.aop.advice.AfterReturningAdvice"></bean>
	<!-- 环绕通知 -->
	<bean class="com.houyitao.aop.advice.MethodInterceptor" id="myInterceptor"></bean>
	<!--异常通知 -->
    <bean class="com.houyitao.aop.advice.ThrowsAdvice" id="myThrowsAdvice"></bean>
    <!-- 过滤通知(适配器) -->
    <bean class="org.springframework.aop.support.RegexpMethodPointcutAdvisor" id="myAfter2">
    <property name="advice" ref="myAfter"></property>
    <property name="pattern" value=".*buy"></property>
    </bean>
	<!--有代理工厂来组装目标对象及通知 -->
	<bean id="bookProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
		<!-- 目标对象 -->
		<property name="target" ref="bookBiz"></property>
		<!-- 代理工厂生产的代理需要实现的接口列表 -->
		<property name="proxyInterfaces">
			<list>
				<value>com.houyitao.aop.biz.IBookBiz</value>
			</list>
		</property>
		<property name="interceptorNames">
			<list>
				<value>myBefore</value>
				<!-- <value>myAfter</value> -->
				<value>myAfter2</value>
				<value>myInterceptor</value>
				<value>myThrowsAdvice</value>
			</list>
		</property>
	</bean>
</beans>


过滤通知(适配器)
org.springframework.aop.support.RegexpMethodPointcutAdvisor
处理买书返利的bug
spring-context.xml

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

package com.houyitao.aop.test;

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

import com.houyitao.aop.biz.IBookBiz;
import com.houyitao.ioc.web.OrderAction;
import com.houyitao.ioc.web.UserAction;

public class AopTest {

	public static void main(String[] args) {
		ApplicationContext springContext=new ClassPathXmlApplicationContext("/spring-context.xml");
		IBookBiz bean = (IBookBiz) springContext.getBean("bookProxy");
		boolean buy=bean.buy("土狗", "小黄书", 18d);
        bean.comment("土狗", "肾虚");
	
	
	}
	
}

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

异常结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值