spring之AOP

一、AOP介绍

1.AOP关键性概念:

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

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

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

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

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

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

2.如何实现AOP

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

二、前置通知

价值:创建session,开启事务

将相关资料导入

MyMethodBeforeAdvice类:

/**
 * 前置通知
 * 调用项目中的某一接口实现类的方式时,将类名.方法名,携带的参数,作为日志存储到数据库。
 * @author Administrator
 *
 */
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);
 
	}

}

IBookBiz类:


public interface IBookBiz {
	// 购书
	public boolean buy(String userName, String bookName, Double price);
 
	// 发表书评
	public void comment(String userName, String comments);
}

BookBizImpl类:


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类:

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:

<bean name="bookBiz" class="com.lv.aop.biz.imp1.BookBizImpl"></bean>

测试:

public class AopTest {
	public static void main(String[] args) {
		ApplicationContext applicationContext=new ClassPathXmlApplicationContext("/spring-context.xml");
		IBookBiz bookBiz=(IBookBiz) applicationContext.getBean("bookBiz");
		bookBiz.buy("小小", "库里", 12.4d);
		bookBiz.comment("小小", "压力噶呀");
	}
 
}

运用前置通知:

 配置文件中spring-context.xml:

<!-- 前置通知 -->
    <bean name="myBefore" class="com.lv.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.lv.aop.biz.IBookBiz</value>
            </list>
        </property>
        <property name="interceptorNames">
            <list>
                <value>myBefore</value>
            </list>
        </property>
    </bean>

拿到代理对象:

public class AopTest {
    public static void main(String[] args) {
        ApplicationContext applicationContext=new ClassPathXmlApplicationContext("/spring-context.xml");
        IBookBiz bookBiz=(IBookBiz) applicationContext.getBean("proxyFactoryBean");

//        这个buy是先去获取前置通知的代码,再去调用目标对象的业务代码
        bookBiz.buy("小小", "库里", 12.4d);
        bookBiz.comment("小小", "压力噶呀");
    }

}

结果:

 三、后置通知

后置通知一般放在方法结尾,有返回值

价值:事务提交,关闭session

MyAfterReturningAdvice类:


/**
 * 后置通知
 * @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);
	}
 
}

进行配置spring-context.xml:

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

测试结果:

 前置通知与后置通知专注于业务代码  

四、环绕通知

 价值:包含了前置通知与后置通知

MyMethodInterceptor:


/**
 * 环绕通知
 * @author Administrator
 *
 */
public class MyMethodInterceptor implements MethodInterceptor {
//	invocation:可以执行被代理的目标对象的业务方法
	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);
		Object returnValue = invocation.proceed();
		String msg2 = "【环绕通知】:目标对象所调用的方法的返回值:" + returnValue;
		System.out.println(msg2);
		return returnValue;
	}
 
}

进行配置:

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

运行结果;

五、异常通知

 价值:处理异常数据,事务回滚

MyThrowsAdvice类;


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

配置:

 

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

运行测试代码,故意给出错误的数据,会运行异常通知:

public class AopTest {
    public static void main(String[] args) {
        ApplicationContext applicationContext=new ClassPathXmlApplicationContext("/spring-context.xml");
        IBookBiz bookBiz=(IBookBiz) applicationContext.getBean("proxyFactoryBean");
        bookBiz.buy("小小", "库里", -12.4);
        bookBiz.comment("小小", "压力噶呀");
    }
}

结果:

六、过滤通知

过滤具有后置通知的buy方法、del方法

<!-- 过滤通知 -->
    <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>
                <value>.*del</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.lv.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>

 测试结果:

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值