spring之AOP

AOP实战详解

AOP:

    即面向切面编程

如何实现AOP

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

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

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

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

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

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

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

案例代码:
BookBizImpl.java

package com.liyi.aop.biz.impl;

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

}

IBookBiz

package com.liyi.aop.biz;

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

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

MyMethodBeforeAdvice

package com.liyi.aop.advice;

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

import org.springframework.aop.MethodBeforeAdvice;
/**
 * 买书、评论前加系统日志
 * @author 224李毅
 *
 */
public class MyMethodBeforeAdvice implements MethodBeforeAdvice {

	@Override
	public void before(Method arg0, Object[] arg1, Object arg2) throws Throwable {
		String clzName = arg2.getClass().getName();
		String methodName = arg0.getName();
		String params = Arrays.toString(arg1);
		System.out.println("系统日志:"+clzName+"."+methodName+"("+params);
	}

}

MyAfterReturningAdvice

package com.liyi.aop.advice;

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

import org.springframework.aop.AfterReturningAdvice;

public class MyAfterReturningAdvice implements AfterReturningAdvice {

	@Override
	public void afterReturning(Object arg0, Method arg1, Object[] arg2, Object arg3) throws Throwable {
		String clzName = arg3.getClass().getName();
		String methodName = arg1.getName();
		String params = Arrays.toString(arg2);
		System.out.println("后置通知:"+clzName+"."+methodName+"("+params);

	}

}

MyMethodInterceptor

package com.liyi.aop.advice;

import java.util.Arrays;

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

public class MyMethodInterceptor implements MethodInterceptor {

	@Override
	public Object invoke(MethodInvocation arg0) throws Throwable {
		String clzName = arg0.getThis().getClass().getName();
		String methodName = arg0.getMethod().getName();
		String params = Arrays.toString(arg0.getArguments());
		//returnValue是代理对象调用目标对象方法的返回值
		System.out.println("环绕通知:"+clzName+"."+methodName+"("+params+")");
		Object returnValue = arg0.proceed();
		System.out.println("环绕通知:"+clzName+"."+methodName+"("+params+")"+"方法调用的返回值"+returnValue);
		return returnValue;
	}

}

MyThrowsAdvice

package com.liyi.aop.advice;

import org.springframework.aop.ThrowsAdvice;

import com.liyi.aop.exception.PriceException;

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

PriceException

package com.liyi.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);
	}
	
}

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">
	
	
	<bean id="userBiz" class="com.liyi.ioc.biz.impl.UserBizImpl1"></bean>
	<bean id="userAction" class="com.liyi.ioc.web.UserAction">
		<!-- <property name="uid" value="22"></property> <property name="uname" 
			value="zs"></property> -->
		<property name="userBiz" ref="userBiz"></property>
		<constructor-arg name="uid" value="22"></constructor-arg>
		<constructor-arg name="uname" value="zs"></constructor-arg>
		<property name="hobby">
			<list>
				<value>篮球</value>
				<value>RAp</value>
				<value>奥迪</value>
			</list>
		</property>
	</bean>
	<!-- aop的知识点 -->
	<!-- 目标 -->
	<bean id="bookBiz" class="com.liyi.aop.biz.impl.BookBizImpl"></bean>
	<!-- 通知 -->
	<bean id="myMethodBeforeAdvice" class="com.liyi.aop.advice.MyMethodBeforeAdvice"></bean>
	<bean id="myAfterReturningAdvice" class="com.liyi.aop.advice.MyAfterReturningAdvice"></bean>
	<bean id="myMethodInterceptor" class="com.liyi.aop.advice.MyMethodInterceptor"></bean>
	<bean id="myThrowsAdvice" class="com.liyi.aop.advice.MyThrowsAdvice"></bean>
	<bean id="myAfterReturningAdvicePlus" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
		<property name="advice" ref="myAfterReturningAdvice"></property>
		<!-- <property name="pattern" value=".*buy"></property> -->
		<property name="patterns">
			<list>
				<value>.*buy</value>
			</list>
		</property>
	</bean>
	
	
	<!-- 代理對象=目標+通知 -->
	<bean id="bookBizProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
		<property name="target" ref="bookBiz"></property>
		<property name="proxyInterfaces">
			<list>
				<value>com.liyi.aop.biz.IBookBiz</value>
			</list>
		</property>
		<property name="interceptorNames">
			<list>
				<value>myMethodBeforeAdvice</value>
				<!-- <value>myAfterReturningAdvice</value> -->
				<value>myAfterReturningAdvicePlus</value>
				<value>myMethodInterceptor</value>
				<value>myThrowsAdvice</value>
			</list>
		</property>
	</bean>
</beans>

测试:

package com.liyi.aop.test;

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

import com.liyi.aop.biz.IBookBiz;

public class Demo1 {
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext("/spring-context.xml");
//		IBookBiz bean = (IBookBiz) context.getBean("bookBiz");
//		System.out.println(bean.getClass());
		
		IBookBiz bean = (IBookBiz) context.getBean("bookBizProxy");
//		System.out.println(bean.getClass());
		
		//报错之后,程序终止
		 
		bean.buy("清洗", "圣墟", 66d);
		bean.comment("清洗", "真的虚");
	}
}

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值